【问题标题】:Update state using array.find for redux return reference or value?使用 array.find 更新状态以获取 redux 返回引用或值?
【发布时间】:2022-01-20 03:28:48
【问题描述】:

我正在关注官网的教程。

我知道状态是不可变的,reducer中的操作实际上是创建一个新的状态副本,修改它并替换原来的。

我在想: 难道不是要删除数组中的条目(exisitngPost)并推入一个新条目吗?由于 state.find() 应该按值而不是引用返回。我弄错了吗?还是与reducer逻辑有关?

tutorial link

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

【问题讨论】:

    标签: arrays reactjs redux


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-30
      • 2018-09-28
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      • 2019-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多