reactjs - React Redux -> 为什么我得到 TypeError: state.item is not iterable
问题描述
所以我试图将对象添加到我的 redux 商店,但显然我做错了什么。首先我在这里定义我的对象:
const items=[
{
name: 'Blue Dress',
Price: 540,
},
{
name: 'Red Dress',
Price: 600,
}]
然后我将它们映射到 return 语句中:
return(
<div>
{items.map(product=>
<div}>
<h1>{product.name}</h1>
<h2>{product.Price}</h2>
<button onClick={()=>buyProduct(product)}>Buy</button>
</div>)}
</div>
)
然后在按下返回语句中生成的按钮后,我调用以下函数,即动作触发器:
const buyProduct=(productAdded)=>{
store.dispatch({type:"buy", payload: productAdded})
}
然后这是我的减速器:
const reducer=function(state=items, action){
if(action.type==='buy')
{
return {...state, items: [...state.items, action.payload]}
}
return state;
这些是我的商店声明和订阅:
const store = createStore(reducer, 0)
store.subscribe(()=>{
console.log('Store is now: ', store.getState())
})
为什么我会收到 typeError,我该如何解决?
解决方案
您需要使用react-redux库。因为你的 React 组件不知道 redux 中的值发生了变化。
因此,items
组件内部不是数组。
推荐阅读
- node.js - 我在 PWA 应用程序中工作,我想直接在打印机上打印一些表格
- lambda - ILoggingBuilded.AddConsole() 适用于一个项目,但不适用于同一解决方案的第二个项目
- javascript - 在整个表单上应用 onChange 事件
- c - 为什么低优先级进程会影响高优先级进程的延迟?
- grafana - InfluxDB 根据标签对所有最新值求和
- sockets - 从 SuSE SLES 12 中的 maraidab 10.2.29 -> 10.3.31 升级后无法连接套接字
- java - 如何在 Spring Boot 中使用 Dtos 修复具有关系的类的输出?
- xcode - 安装 cocoapods 的问题
- node.js - prometheus 无法从 localhost 访问指标
- javascript - 从 JSON 数组解析,两个对象