redux not calling mapStateToProps on store update


更新

状态时不要使用push。使用concat

我正面临这个非常奇怪的问题,请考虑这个减速器:

export default function(state = null, action) {
  console.log("Current State: ",state);
  // on performing actions, it gives me:
  // Current State: null
  // Current State: Array [{}]
  // Current State: Array [{}] -- all good
  if(state === null) {
      state = [
          {id: 1, title: "Java"}
      ];
  }
  // UPDATED PART. FORGOT TO MENTION IT BEFORE
  if(Action.type == "UPDATE_LIST") {
     state.push( Action.payload ); // don't do that, this'll mutate your array and states are immutable
  }
  /////////////
  return state; // this is the main problem
}

上面的代码不会在我的组件中调用mapStateToProps。但是,像下面这样修改上面的化简器确实会调用mapStateToProps

return []; // instead of return state;

return [ {id: 1, title: "Python"} ]; // instead of return state;

我在这两种情况下都返回了数组的实例 [ state & [] ],但只有后一种在我的组件中调用mapStateToProps

这很奇怪,我不知道我应该怎么做才能解决这个问题。

redux 的目的是确保你的状态不是直接可变的。由于数组和对象在 Javascript 中是通过引用传递的,因此您的代码正在尝试直接改变状态对象。这是不正确的。

始终通过返回新状态来改变状态。喜欢这个:

export default function(state = null, action) {
  let newState = [...state];
  if(state === null) {
      newstate = [
          {id: 1, title: "Java"}
      ];
  }
  return newState;
}

这样做:

 if(state === null) {
      state = [
          {id: 1, title: "Java"}
      ]; 
      return state;
  }
  return state;

最新更新