首页 > 解决方案 > 更新数组对象内的值

问题描述

我只想name用用户输入的新名称替换。我正在使用 react redux 打字稿,事实证明它非常困难。所有传入的参数都有效,newNameand index,我只需要更新数组对象然后返回它,只更改索引对象中的名称。

我的代码:

行动:

export const updateName = (newName: string, index: number) => (
  dispatch: (arg0: { type?: string; newName: string; index: number }) => any
) => {
  dispatch({
    type: UPDATE_NAME,
    newName,
    index
  });
};

减速器:

case UPDATE_NAME:
      return {
        ...state
        items[action.index].name: action.newName,

      };

状态如下所示:

items: Array(50)
0: {id: "1d0b1095-f0b4-4881-8d5e-74c86d5beee2", name: "A Ipsum Debitis", participants: {…},
1: {id: "7384a574-1592-484e-9404-e876bf45410c", name: "Distinctio Blanditiis Voluptatibus Ut", participants: {…},

标签: javascriptarraysreactjstypescriptreact-redux

解决方案


除了浅拷贝状态对象外,您还需要浅拷贝任何正在更新的嵌套状态,即正在更新state.items的特定数组元素。

case UPDATE_NAME:
  return {
    ...state,
    items: state.items.map((el, i) => i === action.index ? {
      ...el,
      name: action.newName,
    } : el),
  };

推荐阅读