【发布时间】:2022-01-20 03:28:48
【问题描述】:
我正在关注官网的教程。
我知道状态是不可变的,reducer中的操作实际上是创建一个新的状态副本,修改它并替换原来的。
我在想: 难道不是要删除数组中的条目(exisitngPost)并推入一个新条目吗?由于 state.find() 应该按值而不是引用返回。我弄错了吗?还是与reducer逻辑有关?
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
【问题讨论】: