Redux Toolkit历史API推送



在某些react/redux应用程序中,必须在调度某个操作后转换到路由。就我而言,我正处于这种情况。让我给你看一个状态切片的缩减器。

nextStep: (state, action) => {
const { steps } = state;
if (steps[state.currentTopNavStep][state.currentStep + 1]) {
state.currentStep++;
} else {
state.currentTopNavStep++;
state.currentStep = 0;
}
if (action.payload.history) {
const nextStep = steps[state.currentTopNavStep][state.currentStep];
const { gendersMatch, valuesExist } = nextStep;
let realNextStep;
if (
(valuesExist && valuesExist(state, fbObject)) ||
(gendersMatch && gendersMatch(state))
) {
state.currentStep++;
realNextStep = steps[state.currentTopNavStep][state.currentStep];
} else {
realNextStep = nextStep;
}
const newRoute = realNextStep.route;
action.payload.history.push(newRoute.path);
}
}

在最后一行中,我想将一条新的路由推送到历史记录中,当调度此操作时,我会将其作为有效负载。我想将reducer内部的逻辑移动到中间件中。reduxToolkit提供createAsyncThunk功能。我想要这样的东西:

const nextStep = createAsyncThunk(
'state/nextStep',
async (history, thunkAPI) => {
const { state } = thunkAPI.getState();
const { steps } = state;
if (steps[state.currentTopNavStep][state.currentStep + 1]) {
state.currentStep++;
} else {
state.currentTopNavStep++;
state.currentStep = 0;
}
if (history) {
const nextStep = steps[state.currentTopNavStep][state.currentStep];
const { gendersMatch, valuesExist } = nextStep;
let realNextStep;
if (
(valuesExist && valuesExist(state, fbObject)) ||
(gendersMatch && gendersMatch(state))
) {
state.currentStep++;
realNextStep = steps[state.currentTopNavStep][state.currentStep];
} else {
realNextStep = nextStep;
}
const newRoute = realNextStep.route;
const res = await history.push(newRoute.path);
return res; //this will be the action payload
}
}
);  

然后在ExtraReducer:内部使用

extraReducers: {
[nextStep.fullfilled]: (state, action) => {
//Here I face the problem, how to handle it in the reducer
return action.payload;
},
},

有人能帮我处理这个案子吗

问题是中间件不能改变状态
您将不得不分别进行这些操作:

  • 减速器改变状态
  • 中间件会产生副作用

此外,createAsyncThunk不是正确的工具。cAT的目的是有一个thunk;挂起";动作,然后是";满足";或";被拒绝";行动你在这里似乎根本没有用
您要么需要手动编写一个普通的thunk,它首先调度一个操作,然后该调度获得新状态,然后进行副作用,要么您必须自己为此编写一个中间件(这也很简单,文档中也有相关示例(。

最新更新