【问题标题】:update value inside array object更新数组对象内的值
【发布时间】:2021-03-16 15:31:28
【问题描述】:

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

我的代码:

行动:

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: {…},

【问题讨论】:

    标签: javascript arrays reactjs typescript react-redux


    【解决方案1】:

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

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

    【讨论】:

    • 我收到此消息“(参数)el: never 传播类型只能从对象 types.ts(2698) 创建”
    • @artworkjpm 没错,您需要输入地图回调函数。似乎el 的类型类似于{ id: string, name: string, participants: any }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 2018-09-27
    • 2021-07-08
    相关资源
    最近更新 更多