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



我目前正在尝试使用Redux reducer更新文本值。然而,我有麻烦弄清楚我将如何修改数组中特定对象的文本。以下是目前为止的内容:

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

来命名

最新更新