【问题标题】:Update array item in the reducer在 reducer 中更新数组项
【发布时间】:2019-08-18 14:04:28
【问题描述】:

在我的减速器状态下,我有数组

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
                    }
                })
            }  

在上面的例子中,我错误地代替了一个地面推杆装载机,它起作用了,我不知道它是如何起作用的。但是当我这样尝试时,它不会......

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

【问题讨论】:

  • 如果key和value相同,可以省略第二个参数:newName: newName is the same as newName,

标签: javascript reactjs react-native redux


【解决方案1】:

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

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

          return el;
        })
      };

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

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

【讨论】:

    【解决方案2】:

    你应该像这样使用 reduce 语法:

     return{
                ...state,
                grounds: state.groundgrounds.reduce((newGrounds, ground) => {
                    if(ground.id === action.id) {
                        newGrounds.push({
                            ...ground,
                            name: action.name
                        })
                     } else {
                            newGrounds.push(ground)
                     }
                    return newGrounds;
                 }, [])
            }  
    

    【讨论】:

      猜你喜欢
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 2016-08-16
      • 1970-01-01
      • 2019-04-17
      • 2022-01-05
      • 1970-01-01
      相关资源
      最近更新 更多