javascript - 更新reducer中的数组项

标签 javascript reactjs react-native redux

在我的 reducer 状态下,我有数组

grounds: [
   {
     name: 'name1',
     id: 123
   }
   {
     name: 'name2',
     id: 456
   }
   {
     name: 'name3',
     id: 789
   }

]

我正在调度一个如下所示的操作

export const renameGound = (newName, id) => {
    return{
        type: RENAME_GROUND,
        newName: newName,
        id: id
    }
} 

我想要的是将名称值更新为具有我作为 action.id 获得的 id 的对象。这是我尝试过的方法,但行不通。

case actionTypes.RENAME_GROUND:
            return{
                ...state,
                grounds: state.grounds.forEach(el => {
                    if(el.id === action.id){
                        el.name = action.newName
                    }
                })
            }  

我错误地在上面的情况下放置了加载程序,而不是理由,它起作用了,我不知道如何起作用,但它起作用了。但是当我像这样尝试时却没有......

如何以正确的方式更新正确的对象?

最佳答案

你能尝试一下reducer中的下一个代码吗?

return {
        ...state,
        grounds: state.grounds.map(el => {
          if (el.id === action.id) {
            return {
              ...el,
              name: action.newName
            };
          }

          return el;
        })
      };

reducer 保持纯净非常重要。你永远不应该改变它的内部参数。

更多信息可以在 Redux documentation 中找到

关于javascript - 更新reducer中的数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57545279/

相关文章:

javascript - 渲染后的 Preact 日志性能

javascript - 选项卡变得无响应

javascript - 从数组派生类型 Typescript

javascript - IE 不支持 HTML5 背景音频

javascript - 从独立指令访问 $scope

IOS Testflight 即使在更新到新版本后也会加载我的应用程序的旧代码

javascript - firebase.firestore.FieldValue.delete() 不删除文档中的字段

javascript - ReactJS 中逻辑 OR 运算符期望为 bool 值的表达式

javascript - React Native - 如果我尝试获取字符串,AsyncStorage 将返回 null

ios - 过多的挂起回调 : 501. 一些挂起的回调可能已经泄露