[英]How to access a reducer state within another reducer when we use “redux-starter-kit”?
Now I made two reducers (student reducer and exam reducer) using redux-starter-kit. 现在,我使用redux-starter-kit制作了两个减速器(学生减速器和考试减速器)。 How can we access the state of exam reducer in student reducer?
如何在学生减速器中访问考试减速器的状态? Also, can we call dispatch function of exam in student reducer to modify the state of exam state?
另外,我们可以在学生减速器中调用考试的调度功能来修改考试状态吗?
examReducer.js ExamReducer.js
const exam = createSlice({
initialState: {
mathScore: 0
},
reducer: {
setMathScore: (state, action) => {
state.mathScore = action.payload;
}
}
});
studentReducer.js studentReducer.js
const student = createSlice({
initialState: {
pass: false
},
reducer: {
setMathScore: (state, action) => {
//try to get math score from exam reducer
state.pass = /*TODO*/ > 70 ? true : false;
}
}
});
store.js store.js
const store = configureStore({
reducer: {
exam: exam.reducer,
student: student.reducer
}
});
You can't "access state of another reducer", because that's not how Redux is meant to work in general. 您不能“访问另一个reducer的状态”,因为那通常不是Redux的工作方式。 There's nothing special about Redux Starter Kit in this regard.
在这方面,Redux入门套件没有什么特别的。
Per the Redux FAQ entry on "sharing state between reducers" : 根据Redux常见问题条目中的“减速器之间的共享状态” :
Many users later want to try to share data between two reducers, but find that
combineReducers
does not allow them to do so.许多用户后来想尝试在两个化
combineReducers
器之间共享数据,但是发现combineReducers
不允许他们这样做。 There are several approaches that can be used:可以使用几种方法:
- 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.这可能需要用您自己的顶级reducer函数来替换
combineReducers
。 You can also use a utility such as reduce-reducers to runcombineReducers
to handle most actions, but also run a more specialized reducer for specific actions that cross state slices.您还可以使用诸如reduce-reducers之类的实用程序来运行
combineReducers
来处理大多数操作,还可以为跨状态切片的特定操作运行更专业的reducer。- Async action creators such as redux-thunk have access to the entire state through
getState()
.异步动作创建者(例如redux-thunk)可以通过
getState()
来访问整个状态。 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.动作创建者可以从状态中检索其他数据并将其放入动作中,以便每个化简器具有足够的信息来更新其自己的状态片。
Also, you definitely cannot dispatch actions inside a reducer . 另外,您绝对不能在reducer内调度动作 。 This is forbidden, and will throw an error.
禁止这样做,将引发错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.