首页 > 解决方案 > 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,我该如何解决?

标签: reactjsredux

解决方案


您需要使用react-redux库。因为你的 React 组件不知道 redux 中的值发生了变化。

因此,items组件内部不是数组。


推荐阅读