Redux Toolkit - 我无法更新 Slice 状态?

2024-02-11

我想更新状态并尝试了几种方法来做到这一点,但我不能。 首先,我得到了一个problem https://stackoverflow.com/questions/65764486/why-reducer-function-return-only-proxy-redux-toolkit通过获取状态,结果,我得到的是代理,而不是状态。

这是由current()redux 工具包提供的功能。 接下来,我遇到的问题是突变主切片状态。

这是一个用于变异的减速器。

reducers: {
    setUser: (state, payload) => {
      console.log("before", current(state)); //init state
      state.currentUser = {
        ...state.currentUser,
        loggined: true,
      };
      console.log("after", current(state)); // here I have new state but...
      
    },
    clearUser: (state) => {},
  },

因此,作为第二个控制台日志,当我想更改页面或只想对状态中的新数据执行某些操作时,我必须声明我想要的内容,方法是useSelector()redux 函数,结果我变老了,状态没有改变。

为什么会发生这种情况?

切片状态示例:

initialState: {
    currentUser: {
      loggined: false,
      isAdmin: false,
      jwt: false,
    },
  },

Thanks!


Reducers https://redux-toolkit.js.org/api/createSlice#reducerscreateSlice使用immer:

该对象将被传递给 createReducer,因此减速器可以安全地“改变”它们所给出的状态。

因此,您可以返回一个新状态的新对象,或者“变异”它而不返回它,从创建Reducer https://redux-toolkit.js.org/api/createReducer

您需要确保要么改变状态参数,要么返回一个新状态,但不能两者兼而有之。

所以你可以这样做:

setUser: (state, payload) => {
  //state here is an immer draft, do not use that to copy current state
  console.log("before", current(state)); //init state
  state.currentUser.loggined = true;
  //not returning anyting
},

不确定如何根据旧状态返回新状态,因为...state复制沉浸草案而不是状态。除非它是一个数组,否则甚至找不到执行此操作的示例。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Redux Toolkit - 我无法更新 Slice 状态? 的相关文章

随机推荐