【发布时间】:2020-07-31 04:21:40
【问题描述】:
Github 问题表明我们可以为此目的使用 TypedAction.defineWithoutPayload,但我找不到任何相关示例。
当 accessToken 存储在有效负载中时,我使用它进行登录。如果令牌存在,则用户可以访问私有页面。
export const login = (token: string) => typedAction("LOGIN", token);
现在,在注销按钮上,我正在尝试执行一个删除有效负载中存储值的操作。在这种情况下,将没有用于调度操作的参数。那么 typedAction 怎么写呢?
如果我使用:
export const logout = () => typedAction("LOGOUT");
我开始在我的减速器的有效负载上收到一个错误,该属性在类型注销时不存在。
这是我的减速器:
export const tokenReducer = (
state: IState['token'] = null,
{ type, payload }: AppAction,
): typeof state => {
switch (type) {
case 'LOGIN':
return payload;
case 'LOGOUT':
return null;
default:
return state;
}
};
代码沙盒:https://codesandbox.io/s/keen-brook-kntkm?file=/src/store/actions/login.ts:50-118
电子邮件:c@c.com 密码:检查
编辑:
export interface IState {
token: string | null;
}
const initialState: IState = {
token: null
};
如果我按照 IDE 的建议使用 state: typeof initialState 或 state = initialState,则 action.payload 出错:
Type 'string' is not assignable to type 'IState'.ts(2322)
如果我尝试state: initialState那么显然:
'initialState' refers to a value, but is being used as a type here. Did you mean 'typeof initialState'?ts(2749)
``
【问题讨论】:
-
在您的代码沙箱中,您似乎已经有
typedAction处理任何有效负载操作;那不工作吗?您是否在执行export const logout = () => typedAction("LOGOUT");之类的操作时遇到编译器错误?由于动作是不变且无参数的,您甚至可以将其作为常量而不是动作创建者。 -
实际上,该行有效,但随后我在
Property 'payload' does not exist on type '{ type: "LOGOUT"; } | { type: "LOGIN"; payload: string; }'.ts(2339)@Jacob 的有效负载上的 tokenReducer 中开始收到错误 -
将单重重载更改为
export function typedAction<T extends string>(type: T): { type: T, payload: void };是否有效?分叉:codesandbox.io/s/vigorous-wescoff-qf4h7?file=/src/store/actions/… -
不,它仍然给出相同的错误,以及其他错误,如“预期 1 个参数,但得到 2 个”@Jacob
-
如果
initialState是IState类型,为什么不使用IState类型而不是typeof?如果您尝试获取令牌变量的类型,请使用const tokenReducerInitialState: IState['token'] = null。
标签: javascript reactjs typescript redux react-redux