how to show the initial state of the store in react-redux?

0

Good afternoon friends, I introduce myself to this community, I have a question I hope you can clarify,

How do I show the initial status of the store in react-redux ?

I have a simple component with a <h1> in react , which I will place a onClick so that when I click on it I change that title for another, in the store I have the initial state text:"titulo" ; How do I display this title on the <h1> tag that I have in react ?

Here the component code:

import React from 'react'

import {connect} from 'react-redux'

class TodoApp extends React.Component {


    render() {

        return(
            <div>
                <h1 onClick={this.cambio}> {this.props.text} </h1>
            </div>
        )
    }
}

const mapStateToProps = state => {
    return {
        text: state.text
    }
}

const mapDispatchToProps = dispatch => {
    return {
        cambio(text) {
            dispatch({
                type: "CAMBIAR",
                text:"se cambio"
            })
        }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(TodoApp)
    
asked by Juan Carlos Rodriguez W. 24.08.2017 в 20:14
source

2 answers

0
import React from 'react';

import { connect } from 'react-redux';

const TodoApp = ({ cambio, text }) => {
  return (
    <div>
      <h1 onClick={cambio}> {text} </h1>
    </div>
  );
};

const mapStateToProps = state => {
  return {
    text: state.text
  };
};

const mapDispatchToProps = dispatch => {
  return {
    cambio(text) {
      dispatch({
        type: "CAMBIAR",
        text:"se cambio"
      });
    }
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(TodoApp);

With an arrow component you can try like this.

    
answered by 29.08.2017 в 10:24
0

Mira I fixed your problem here: link tell me if it works for you, you have several problems, you must make sure you are giving the correct data to the redux store:

    const estadoInicial =
       {
           text: 'inicial'
       };

   const reducer = (state,action) => {
     switch (action.type) {
       case "CAMBIAR":
         return {text: action.text}
         break;
       default:
         return state;

     }
   }


   const store = createStore(
     reducer,
     estadoInicial,
     window.__REDUX_DEVTOOLS_EXTENSION__ &&                      window.__REDUX_DEVTOOLS_EXTENSION__()
   )

   ReactDOM.render(
     <Provider store={store}>
       <TodoApp />
     </Provider>, document.getElementById('root'));

second, the dispatch comes by props, so the onclick must be

    onClick={this.props.cambio}

and voila, this works

    
answered by 08.01.2018 в 19:19