redux-反应简单的你好世界

时间:2016-02-21 02:01:16

标签: javascript reactjs redux react-redux

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

2 个答案:

答案 0 :(得分:2)

您直接指定&#34;州&#34;在你的reducer中,它直接改变它。您需要返回Object.assign({}, state, {message:"hello world"});

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

答案 1 :(得分:0)

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

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

是ES6传播运营商。