是否使用array.find为redux返回引用或值更新状态



我在官方网站上学习教程。

我知道状态是不可变的,reducer中的操作实际上是创建状态的新副本,对其进行修改并替换原始副本。

我在想:难道不应该删除数组中的条目(exisitngPost(,然后推送一个新条目吗?As state.find((应按值而不是引用返回。我弄错了吗?还是与reductor逻辑有关?

教程链接

const postsSlice = createSlice({
name: 'posts',
initialState,
reducers: {
postAdded(state, action) {
state.push(action.payload)
},
postUpdated(state, action) {
const { id, title, content } = action.payload
// where i find confused<<<<<<<<<<<<<<<<<<<
const existingPost = state.find(post => post.id === id)
if (existingPost) {
existingPost.title = title
existingPost.content = content
}
}
}
})
export const { postAdded, postUpdated } = postsSlice.actions
export default postsSlice.reducer

state.find返回处于状态的对象,如果它不是基元,则该对象将是引用。因此,在RTK immer reducer中,您可以对其进行修改,并且在reducer运行后,将为您创建一个具有应用更改的新的不可变副本,而不是修改原始副本。

最新更新