这是一个例子:
const user = createSlice({
name: 'user',
initialState: { name: '', age: 20 },
reducers: {
setUserName: (state, action) => {
state.name = action.payload // mutate the state all you want with immer
}
},
// "map object API"
extraReducers: {
[counter.actions.increment]: (state, action) => {
state.age += 1
}
}
})
我可以访问计数器状态吗?
假设我只想在计数器为 30 时增加年龄。否则,我需要在
useEffect
中的计数发生变化时进行监听。钩子(Hook)并调度一些将处理年龄增量(?)的 Action 。换句话说,根据当前全局状态使用
redux-toolkit
计算状态切片的最佳方法是什么? ?
最佳答案
这在 the Redux FAQ entry on sharing state between reducers 中有介绍.
粘贴关键点:
- If a reducer needs to know data from another slice of state, the state tree shape may need to be reorganized so that a single reducer is handling more of the data.
- You may need to write some custom functions for handling some of these actions. This may require replacing
combineReducers
with your own top-level reducer function. You can also use a utility such asreduce-reducers
to runcombineReducers
to handle most actions, but also run a more specialized reducer for specific actions that cross state slices.- Async action creators such as
redux-thunk
have access to the entire state throughgetState()
. An action creator can retrieve additional data from the state and put it in an action, so that each reducer has enough information to update its own state slice.
关于reactjs - 有没有办法在 createSlice 中访问全局状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60739372/