首页 > 解决方案 > reducer 不更新状态

问题描述

我的应用程序中有简单的流程。请求完成后,我正在调用带有有效负载的操作:

export const setVoteFlagCurrentPoll = () => dispatch => {
  dispatch({
    type: SET_VOTE_FLAG_CURRENT_POLL,
    payload: true
  })
}

然后在 reducer 中,我更改了 poll 对象中的一个变量,如下所示:

{
  idsurvey: 10, 
  topic: "random poll question", 
  answers: Array(4), 
  voted: false
}

减速机本身:

case SET_VOTE_FLAG_CURRENT_POLL:
      return {...state, pollData: {...state.pollData, voted: action.payload}};

我的问题是变量 'voted' 没有改变它的值。它仍然是“假的”。有趣的是,我可以将那个recuder记录为:console.log({...state, pollData: {...state.pollData, voted: action.payload}});并且它可以工作..它的记录被投票为真。为什么会这样?

标签: reactjsredux

解决方案


好的,我想通了。似乎 mapStateToProps 函数写得不好..

之前(不工作):

const = ({user}) => ({user}); // its returning whole user reducer

之后(现在工作):

const mapStateToProps = state => {
  return {
    user: state.user //same as above (I didnt want to change the code in other components..)
    pollData: state.user.pollData //pulling pollData directly
  }
}

希望能帮助到你。


推荐阅读