2016-02-21 26 views
3

我是新来的REDX - 为什么mapStateToProps被调用,组件更新显示'你好世界'?还原 - 反应简单你好世界

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

你在你的减速,这直接变异直接分配给“国家”。您需要返回Object.assign({}, state, {message:"hello world"});

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

+1

现在很棘手。我在尝试调试问题时错过了它。这是使用es6传播运算符'return {... state,{message:“hello”};'在我看来这更明显且可读的这里的潜在好理由。 –

+0

是的,变异状态是“为什么我的组件没有更新?”的第一个答案,这就是为什么它会进入我正在处理的Redux FAQ页面。 – markerikson

0

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

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

这是ES6蔓延运营商。