我正在学习打字稿,并且想实现一个简单的React / Redux应用程序。当我使用同步操作时,它可以正常工作,但是异步操作存在问题。我正在关注官方的redux教程。
首先,我声明会话的状态
export interface UserSessionState {
loggedIn: boolean;
}
然后我声明动作的接口
interface UpdateSessionAction {
type: 'USER_LOGIN';
payload: boolean;
}
我用联合类型导出它们
export type UserActionTypes = UpdateSessionAction;
然后我有实际的行动
export function updateSession(loggedIn: UserSessionState) {
return {
type: 'USER_LOGIN',
payload: loggedIn,
};
}
我有一个假的api呼叫
function api() {
return Promise.resolve(true);
}
最后登录
export const userLogin = (): ThunkAction<
void,
{},
{},
AnyAction
> => async (dispatch: ThunkDispatch<{}, {}, AnyAction>) => {
const res = await api();
dispatch(updateSession({ loggedIn: res }));
};
在reducer中,我只是初始化状态
initialState: UserSessionState = {loggedIn: false}
然后,我为减速器执行常规的redux任务。
最后,在我的商店中,我调用初始操作以检查状态
store.dispatch(userLogin());
我不断收到此错误:
Argument of type 'ThunkAction<Promise<void>, {}, {}, AnyAction>' is not assignable to parameter of type 'AnyAction'.
Property 'type' is missing in type 'ThunkAction<Promise<void>, {}, {}, AnyAction>' but required in type 'AnyAction'.
我想念一个,type
但我不知道我做错了什么。
简而言之:
之所以出现此错误,是因为userLogin()
函数返回的是ThunkAction
,而该缺失type
为什么会这样呢?
dispatch应该接受type的参数AnyAction
。
AnyAction
是redux类型,它进行扩展Action
(具有必填属性 type
)。
这来自当前的redux types文件
export interface Action<T = any> {
type: T
}
/**
* An Action type which accepts any other properties.
* This is mainly for the use of the `Reducer` type.
* This is not part of `Action` itself to prevent users who are extending `Action.
*/
export interface AnyAction extends Action {
// Allows any extra properties to be defined in an action.
[extraProps: string]: any
}
如何解决?
使用ThunkDispatch
type代替redux的standard Dispatch
。以下示例以及更多内容可以在此要旨中找到
const mapDispatchToProps = (dispatch: ThunkDispatch<MyState, void, Action>) => {
return {
onRequestClick: (arg: any) => dispatch(myAsyncAction(arg)),
};
}
另外,看到这个文章,部分 map调度道具
感谢您的回答,
export function updateSession(loggedIn: UserSessionState)
但是在这里我要说的是,有效负载loggedIn
必须为UserSessionState的形状,然后才具有此处操作的类型,对interface UpdateSessionAction { type: 'USER_LOGIN'; payload: boolean; }
吗?谢谢!现在我知道了,
Argument of type 'boolean' is not assignable to parameter of type 'UpdateSessionAction
但是我仍然会接受您的回答,因为它是正确的。我需要了解有关打字稿的更多信息,也许我急于将事情直接转移到异步操作中。:)