javascript - 使用 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
解决方案
push
返回length
mutated 的新值array
。使用concat
而不是返回一个新数组
results : state.results.concat(item)
让我们假设以下代码
results : state.results.push('foo')
假设 results
有 a length
,5
上面的代码将断言为
results : 5
下次您尝试push
results
这样做时,您的编译器会是什么样子
5.push('foo')
推荐阅读
- node.js - 查找字符串并删除行 - Node.JS
- mysql - 循环运行多个 Sql 命令
- react-select - 如何仅使用 react-select onChange 事件和 value 道具中的值?
- c - 如何将十六进制 ASCII 值保存到 C 中的数组(缓冲区)中?
- magento - 具有可下载选项的 Magento 2.2 可配置产品:电子邮件不包含下载链接
- ruby-on-rails - 无法使用 FactoryBot 在 Rspec 中建立 has_and_belongs_to_many 关系
- r - RStudio 连接服务器与 Power BI
- javascript - 异步问题,无法在 .then 之后运行 shelljs 命令
- java - 使用 ImageIO.read() 时忽略 Alpha 通道
- ddev - ddev v1.3.0 中的 ssh 客户端去哪儿了?