用例:我有一个用JHipster生成的react应用程序。我需要从API获取数据,映射到表单合同,然后提交表单。
问题:JHipster生成的reducer代码没有返回Promise,那么我如何知道reducer操作何时完成?让实体更新状态后如何调用函数?
获取实体并返回ICrudGetAction:
export interface IPayload<T> { // redux-action-type.ts (JHipster Code from node_modules)
type: string;
payload: AxiosPromise<T>;
meta?: any;
}
export type IPayloadResult<T> = ((dispatch: any) => IPayload<T> | Promise<IPayload<T>>);
export type ICrudGetAction<T> = (id: string | number) => IPayload<T> | ((dispatch: any) => IPayload<T>);
// Start of my reducer code
export default (state: AdState = initialState, action): AdState => {
switch (action.type) {
case REQUEST(ACTION_TYPES.FETCH_MYENTITY_LIST):
return {
...state,
errorMessage: null,
updateSuccess: false,
loading: true
};
case FAILURE(ACTION_TYPES.FETCH_MYENTITY_LIST):
return {
...state,
loading: false,
updating: false,
updateSuccess: false,
errorMessage: action.payload
};
case SUCCESS(ACTION_TYPES.FETCH_MYENTITY_LIST): {
const links = parseHeaderForLinks(action.payload.headers.link);
return {
...state,
loading: false,
links,
entities: loadMoreDataWhenScrolled(state.entities, action.payload.data, links),
totalItems: parseInt(action.payload.headers['x-total-count'], 10)
};
}
case ACTION_TYPES.RESET:
return {
...initialState
};
default:
return state;
}
};
export const getEntity: ICrudGetAction<IMyEntity> = id => {
const requestUrl = `${apiUrl}/${id}`;
return {
type: ACTION_TYPES.FETCH_ENTITY,
payload: axios.get<IMyEntity>(requestUrl)
};
};
我尝试执行此操作,但是它能给我带来编译错误:
this.props.getEntity(this.props.match.params.id).then((response) => {
// Map to form attributes and call setState
});
我收到错误消息: TS2339:“ IPayload |类型”上不存在属性“ then” ((调度:任何)=> IPayload)'。 属性“ then”在“ IPayload”类型上不存在。
这很有意义,因为我们没有兑现承诺。但是如何更新代码以返回承诺,这样我就不会破坏自动生成的所有内容,同时还能保持redux存储的更新?