redux-react 简单的你好世界

redux-react simple hello world

我是 redux 的新手 - 为什么 mapStateToProps 没有被调用并且组件更新显示 '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')
);

你在你的 reducer 中直接赋值给 "state",这直接改变了它。您需要 return Object.assign({}, state, {message:"hello world"}); 来代替。

另请注意,React-Redux 做了很多工作来确保组件的 mapStateToProps 功能仅在绝对必要时运行。

替换行:return Object.assign(state,{message:"hello world"});

用这个:return {...state, message:"hello world"};

是ES6的展开运算符。