如何解决Redux Toolkit 历史 API 推送
在某些 react/redux 应用程序中,必须在分派某些操作后转换到路由。就我而言,我正是这种情况。让我向您展示一个状态切片的 reducer。
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;
},},
谁能帮我解决这个案子
解决方法
问题是中间件不能改变状态。
你真的必须分开做这些:
- reducer 改变状态
- 中间件有副作用
此外,createAsyncThunk
在这里不是正确的工具。 cAT 的目的是让 thunk 发送“待处理”操作,然后发送“已完成”或“拒绝”操作。你在这里似乎根本没有任何用处。
您要么需要手动编写一个普通的 thunk 来首先调度一个动作,在该调度获得新状态然后执行副作用之后,或者您必须自己为此编写一个中间件(这很简单,因为好吧,文档中有关于这方面的示例)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。