Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用“时如何访问另一个减速器中的减速器状态”;redux初学者工具包;?_Javascript_Reactjs_Redux - Fatal编程技术网

Javascript 使用“时如何访问另一个减速器中的减速器状态”;redux初学者工具包;?

Javascript 使用“时如何访问另一个减速器中的减速器状态”;redux初学者工具包;?,javascript,reactjs,redux,Javascript,Reactjs,Redux,现在我用redux初学者工具包制作了两个减速机(学生减速机和考试减速机)。如何在student reducer中访问考试reducer的状态?另外,我们可以调用student reducer中的考试调度函数来修改考试状态吗 examReducer.js const exam = createSlice({ initialState: { mathScore: 0 }, reducer: { setMathScore: (state, action) => { st

现在我用redux初学者工具包制作了两个减速机(学生减速机和考试减速机)。如何在student reducer中访问考试reducer的状态?另外,我们可以调用student reducer中的考试调度函数来修改考试状态吗

examReducer.js

const exam = createSlice({
 initialState: {
   mathScore: 0
 },
 reducer: {
   setMathScore: (state, action) => {
    state.mathScore = action.payload;
   }
 }
});
const student = createSlice({
 initialState: {
   pass: false
 },
 reducer: {
   setMathScore: (state, action) => {
    //try to get math score from exam reducer
    state.pass = /*TODO*/ > 70 ? true : false;
   }
 }
});
studentReducer.js

const exam = createSlice({
 initialState: {
   mathScore: 0
 },
 reducer: {
   setMathScore: (state, action) => {
    state.mathScore = action.payload;
   }
 }
});
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

const store = configureStore({
  reducer: {
    exam: exam.reducer,
    student: student.reducer
  }
});
您不能“访问另一个reducer的状态”,因为Redux通常不是这样工作的。在这方面,Redux初学者套件没有什么特别之处

根据:

许多用户后来想尝试在两个还原器之间共享数据,但发现
combinereducer
不允许他们这样做。可以使用以下几种方法:

  • 如果一个reducer需要知道来自另一个状态片的数据,则可能需要重新组织状态树形状,以便单个reducer处理更多的数据
  • 您可能需要编写一些自定义函数来处理这些操作。这可能需要使用您自己的顶级减速器功能更换组合减速器。您还可以使用诸如运行
    combinereducer
    之类的实用程序来处理大多数操作,但也可以为跨状态切片的特定操作运行更专门的reducer
  • 异步操作创建者(如)可以通过
    getState()
    访问整个状态。动作创建者可以从状态中检索附加数据并将其放入动作中,以便每个reducer都有足够的信息来更新自己的状态片
此外,您肯定无法在减速机内部调度操作。这是禁止的,并且将抛出错误