Redux Toolkit - 我无法更新 Slice 状态? [英] Redux Toolkit - I can't update Slice state?
问题描述
我想更新状态并尝试了几种方法来做到这一点,但我不能.首先,我在获取状态时遇到了问题,作为结果,我得到了代理,而不是状态.
I wanna update the state and tried few ways to do that, but I can't. First, I got a problem with fetching state, as a result, I got proxy, not a state.
这是由 redux 工具包的 current()
函数修复的.接下来,我遇到的问题是突变主切片状态.
That is fixed by the current()
function by the redux toolkit.
Next, where I have a problem is mutation main slice state.
这是一个用于变异的reducer.
Here is a reducer for mutating.
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()
useSelector() 声明我想要的内容code> redux 函数,结果老了,状态没变.
As a result, as a second console log, I got to state what I want, when I want to change a page or just want to do something with new data in the state, by useSelector()
redux function, as a result, I got old, not changed state.
为什么会这样?
切片状态示例:
initialState: {
currentUser: {
loggined: false,
isAdmin: false,
jwt: false,
},
},
谢谢!
推荐答案
这个对象将被传递给 createReducer,因此reducer 可以安全地变异";他们被给予的状态.
This object will be passed to createReducer, so the reducers may safely "mutate" the state they are given.
所以你可以返回一个新的对象,它是新的状态或者变异"它而不是返回它,来自 createReducer
So you can either return a new object that is the new state or "mutate" it and not return it, from createReducer
您需要确保要么改变 state 参数,要么返回一个新状态,但不能两者兼而有之.
you need to ensure that you either mutate the state argument or return a new state, but not both.
所以你可以这样做:
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
制作了沉浸式草稿的副本,而不是状态的副本.除非它是一个数组,否则甚至找不到这样做的例子.
Not sure how you'd return a new state based on the old one since ...state
makes a copy of the immer draft and not of the state. Can't even find examples of doing this unless it's an array.
这篇关于Redux Toolkit - 我无法更新 Slice 状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!