3

我是 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')
);
4

2 回答 2

2

您直接分配给减速器中的“状态”,这直接改变了它。您需要返回Object.assign({}, state, {message:"hello world"});

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

于 2016-02-21T02:26:17.860 回答
0

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

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

它是 ES6 扩展运算符。

于 2016-12-29T19:04:36.113 回答