首页 > 解决方案 > 使用 redux 更新状态时推送反应的工作

问题描述

以下代码是我在容器中调用这些函数的减速器的代码

const intialState = {
  counter: 0,
  results: []
};

const reducer = (state = intialState, action) => {
  switch (action.type) {
    case "INCREMENT":
      return {
        ...state,
        counter: state.counter + 1
      };

    case "STORE_RESULT": {
      return {
        ...state,
        results: state.results.push(state.counter)
      };
    }
  }
  return state;
};

export default reducer;

我收到以下错误

TypeError: state.results.push is not a function
reducer

1)我在我的项目中使用redux reducer

2)我通过在我的容器中传递我的调度中的类型来更新状态

3)我试图通过推送来更新数组(我知道它返回长度)但我想知道它为什么不工作

4)按照我在javascript中尝试的代码一切正常

var a = {
b:[]
}
a.b.push(11)
//output
1

标签: javascriptreactjsreduxreact-redux

解决方案


push返回lengthmutated 的新值array。使用concat而不是返回一个新数组

results : state.results.concat(item)

让我们假设以下代码

results : state.results.push('foo')

假设 results有 a length5上面的代码将断言为

results : 5

下次您尝试push results这样做时,您的编译器会是什么样子

5.push('foo')

推荐阅读