【问题标题】:Can I bind store's state with a component in react-redux?我可以将商店的状态与 react-redux 中的组件绑定吗?
【发布时间】:2018-12-16 08:50:19
【问题描述】:

我是 react-redux 的新手,我使用 react-redux 创建了一个小型 CRUD 应用程序,当我单击子组件中的添加按钮时,它会从所有输入框中获取数据并在 Reducer 的帮助下更新我的商店数组。

const initialState = {
itemObjectArr:[] }

我的 Reducer 更新这个 itemObjectArr,并在 connect(mapStateToProps)(NeedyChildComponent) 函数的帮助下将它发送给需要的组件。 现在,当我尝试在控制台上打印 state.itemObjectArr 时,真正的问题出现了。

const  mapStateToProps = (state)=>{
console.log(state.itemObjectArr);
return  {itemObject:state.itemObjectArrs}}

上面的代码在控制台上给出了一个错误TypeError: Cannot read property 'itemObjectArrs' of undefined 如果我这样做 console.log(state) 它可以轻松打印包含数组的对象而不会出现任何错误。

我搜索了这个错误但没有得到任何重要的东西,我认为这个商店的状态是不可变的,当它作为参数传递给 mapStateToProps 函数时,mapStateToProps 检查状态的变化,如果它没有得到任何变化,那么它会返回一个错误.也许这正在发生在这里。

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    你的减速器是什么样子的?由于商店在您的组件中以 undefined 的形式返回,因此在我看来,您没有在 switch 语句中定义返回更新前初始状态的 default case执行动作,例如:

    const myReducer = (state, action) => {
      switch (action.type) {
        case 'UPDATE_ITEM_OBJECT_ARR': return { itemObjectArr: [ 1, 2, 3] }
    
        default:
          return initialState;
      }
    }
    

    【讨论】:

    • 感谢现在一切都在完美运行
    猜你喜欢
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    相关资源
    最近更新 更多