我正在使用redux-toolkit进行redux状态管理。这是显示错误的代码
import * as actions from "../../../_redux/entities/entitiesActions";
import { useDispatch } from "react-redux";
import { strict } from "assert";
const dispatch = useDispatch();
const deleteEntity = () => {
// server request for deleting device by id
dispatch(actions.deleteEntity(id)).then(() => { //Error on this line
// refresh list after deletion
dispatch(actions.fetchEntities(entitiesUIProps.queryParams));
});
};
而EntityActions.ts在这里
//EntitiesActions.ts
const {actions} = entitesSlice;
export const fetchEntites = (queryParams:any) => (dispatch:Dispatch) => {
dispatch(actions.startCall({ callType: callTypes.list }));
return requestFromServer
.findEntites(queryParams)
.then(response => {
const { totalCount, entities } = response.data;
dispatch(actions.entitesFetched({ totalCount, entities }));
})
.catch(error => {
error.clientMessage = "Can't find entites";
dispatch(actions.catchError({ error, callType: callTypes.list }));
});
};
export const deleteEntity = (id:string) => (dispatch:Dispatch) => {
dispatch(actions.startCall({ callType: callTypes.action }));
return requestFromServer
.deleteEntity(id)
.then(response => {
dispatch(actions.deviceDeleted({ id }));
})
.catch(error => {
error.clientMessage = "Can't delete device";
dispatch(actions.catchError({ error, callType: callTypes.action }));
});
};
我不知道如何解决此错误。请帮忙! 谢谢!
编辑:
如果我从外部调度中删除了then
块,该错误消失了,但是我担心这会导致嵌套调度在外部调度执行完成之前触发?
const deleteEntity = () => {
// server request for deleting device by id
dispatch(actions.deleteEntity(id));//.then(() => { //Error goes away
// refresh list after deletion
dispatch(actions.fetchEntities(entitiesUIProps.queryParams));
//});
};
答案 0 :(得分:3)
dispatch
函数应该是同步的,因此不能等待。要使其在使用Redux Toolkit时返回Promise,可以使用
const useThunkDispatch = () => useDispatch<typeof store.dispatch>()
const dispatch = useThunkDispatch()
商店是由configureStore
中的@reduxjs/toolkit
创建的。
如果我从外部调度中删除然后阻止,则错误消失了,但是 恐怕这会导致嵌套派遣在外部触发 分派执行完成吗?
是的。