【问题标题】:Is it safe to update redux state outside the slice (in a reusable function)?在切片外更新 redux 状态是否安全(在可重用函数中)?
【发布时间】:2023-01-20 20:03:11
【问题描述】:

在切片外更新 redux 状态是否安全?所以基本上在你的代码中有这样的东西:

export const dataSlice = createSlice({
  name: "data",
  initialState: initState,
  reducers: {
    ...
  }
  extraReducers: (builder) => {
    ...
  }
})
// end of dataSlice

const setData = (
  state: WritableDraft<WritableDraft<IFiltersSlice>>,
  { id, newData }: { id: number; newData: TData }
) => {
  const idIndex = state.dataArr.findIndex((data) => data.id === id)

  if (idIndex !== -1) {
    if (newData.length === 2 && typeof newData[0] === "number" && typeof newData[1] === "number")
      state.dataArr[idIndex].value = newData

    state.dataArr[filterIndex].bounds = newData
  }
}

它对我来说看起来有点粗略,但我试过了,它似乎有效。

另一种方法是从 setData 返回状态,并在切片中再次返回调用函数的结果。但是,既然 redux toolkit 使用了 Immer,我想这也应该没问题吧?

基本上我在代码中发现了这个,我想知道它是否不好(如果是,为什么)。 我们是否也应该在未来关注这一点?

我在网上(或在文档中)找不到与此相关的任何内容。也许我只是错过了它?

无论如何,在 cmets 中欢迎任何意见,并且非常感谢任何good answer它。

非常感谢你!

【问题讨论】:

    标签: reactjs react-redux redux-toolkit immer.js


    【解决方案1】:

    这对我来说似乎很粗略。我在 Redux Toolkit 中使用 extraReducers

    【讨论】:

      猜你喜欢
      • 2021-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-17
      • 2021-02-06
      • 2019-01-19
      • 2019-11-12
      • 2018-06-29
      相关资源
      最近更新 更多