Recently I change to slice and I seeing some odd behavior can someone explain:
const initialState = {
[]
};
export const userSlice = createSlice({
name: "user",
initialState,
reducers: {
loadUsers(state, action) {
state = state.concat(action.payload);
},
},
});
when i do something like this the state wont change and payload dont add to state array
i can go like
for(let i=0; i < action.payload.length; i++) {
state.push(action.payload[i]
}
and everything work fine, then I realized if name the state initial state like:
const initialState = {
users: [],
};
Then I can go like:
state.users = state.users.concat(action.payload);
on loadUsers reducer and this work fine too can someone explain why concat wont work on first attempt when i have initial state of [] without naming it
The problem here is not push
or concat
, but the fact that
state = something
will never do anything.
Redux Toolkit watches the object in the variable state
for modifications - but that assignment throws away that object and puts a new object into the variable instead of changing it.
That cannot be observed.
Instead, you can do
return something
For more information, see Writing Reducers with immer
, especially resetting and replacing state , which says:
A common mistake is to try assigning
state = someValue
directly. This will not work! This only points the local state variable to a different reference. That is neither mutating the existing state object/array in memory, nor returning an entirely new value, so Immer does not make any actual changes.
Adding on to the previous answer, to make one distinction. You should not attempt to mutate the entire state as in the line
State = something
But you can and should mutate state properties in this way, in fact it is one of the major benefits of redux toolkit and immer, so
State.prop = something
Is ok. This is a good time to reiterate this kind of state mutation is only ok in redux toolkit where immer is doing it's work.
Again here is the link to the relevant docs
https://redux-toolkit.js.org/usage/immer-reducers#resetting-and-replacing-state
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.