如何使用 Redux Reducers 更新对象数组中的 属性?

How Do I Update a Property in Array of Objects using Redux Reducers?

我目前正在尝试使用 Redux reducers 更新文本值。但是,我无法弄清楚我将如何修改数组中特定对象的文本。这是我目前所拥有的:

export const teamSlice = createSlice({
  name: "team",
  initialState: {
    teamArr: [
      { id: " 1", text: "", icon: "" },
      { id: " 2", text: "", icon: "" },
      { id: " 3", text: "", icon: "" },
      { id: " 4", text: "", icon: "" },
      { id: " 5", text: "", icon: "" },
      { id: " 6", text: "", icon: "" },
      { id: " 7", text: "", icon: "" },
      { id: " 8", text: "", icon: "" },
      { id: " 9", text: "", icon: "" },
      { id: " 10", text: "", icon: "" },
    ],
  },
  reducers: {
    setTeamSlice: (state, action) => {
      state.teamArr = action.payload
    },
    setPlayerTextSlice: (state, action) => {
      const updatedArr = [...state.teamArr]

      //get object and index position of object
      const player = updatedArr.filter(
        (obj) => obj.id === ???
      )[0]
      const index = updatedArr.indexOf(player)

      //update text of object
      player.text = action.payload

      //update object in array
      updatedArr[index] = player

      //return the new updatedArr as the result
      return updatedArr
    },
  },
})

我想创建的更新文本的函数 属性 是 setPlayerTextSlice。但是,我找不到在调用函数时获取我感兴趣的对象的ID的方法。

我还将从将使用此函数 onChange 的输入字段调用此函数:

<input
        onChange={(e) => setPlayerTextSlice(e.target.value)}
        value={text}
        placeholder={id}
      ></input>

非常感谢任何帮助和建议!

你可以做到

  setPlayerTextSlice: (state, action) => {
      const player = updatedArr.find(
        (obj) => obj.id === action.payload.id
      )
      if (player) {
        player.text = action.payload.text
      }
    },

实际上不需要您的其余代码。

可以用dispatch(setPlayerTextSlice({ id: 5, text: "foo" }))

调用