在某些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);
}
}
在最后一行,我想将一条新路由推入历史记录,在分派此操作时,它将作为有效负载获得。我想将化简器内部的逻辑转移到中间件中。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
}
}
);
然后在extraReducers中使用它:
extraReducers: {
[nextStep.fullfilled]: (state, action) => {
//Here I face the problem, how to handle it in the reducer
return action.payload;
},
},
有人可以帮我解决这个问题吗
问题是中间件一定不能改变状态。
您实际上必须彼此分开执行这些操作:
另外,createAsyncThunk
这里也不是正确的工具。cAT的目的是让一个笨拙的人发出“待处理”的动作,然后发出“完成的”或“被拒绝的”动作。您似乎在这里根本没有任何用处。
您要么需要手工编写一个普通的thunk,然后首先分发一个动作,然后该分发获得新的状态,然后再产生副作用,或者您必须为此自己编写一个中间件(这很简单,因为好吧,文档上有示例)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句