Tom
Tom

Reputation: 8180

redux-react simple hello world

I am new to redux - why doesn't mapStateToProps get called and the component update to show 'hello world'?

http://codepen.io/anon/pen/QyXyvW?editors=0011

const helloReducer = (state= {message:'none'}, action) => {    
 switch (action.type) {
    case 'HELLO':
      return Object.assign(state,{message:"hello world"});
    default:
      return state;
  }  
};
const myApp = Redux.combineReducers({
  helloReducer
});    
const App = ({onClick,message}) => (
  <div>
    <a href="#" onClick={onClick}>click</a><b>{message}</b>
  </div>
);
const mapStateToProps = (state, ownProps) => {
  return {message: state.message}
};
const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    onClick: () => {
      dispatch({type: 'HELLO'})
    }
  }
}   
const ConnectedApp = ReactRedux.connect(
  mapStateToProps,
  mapDispatchToProps
)(App);
let Provider = ReactRedux.Provider;
let store = Redux.createStore(myApp)
let e = React.render(
  <Provider store={store}>
    <ConnectedApp />
  </Provider>,
  document.getElementById('root')
);

Upvotes: 3

Views: 1038

Answers (2)

solanki...
solanki...

Reputation: 5098

replace line : return Object.assign(state,{message:"hello world"});

with this: return {...state, message:"hello world"};

It is ES6 spread operator.

Upvotes: 0

markerikson
markerikson

Reputation: 67489

You're assigning directly to "state" in your reducer, which is mutating it directly. You need to return Object.assign({}, state, {message:"hello world"}); instead.

Also note that React-Redux does a lot of work to make sure that a component's mapStateToProps function only runs when it absolutely has to.

Upvotes: 2

Related Questions