为Redux Store定义initialState的不同方式



我最近遇到了这个例子:

state.d.ts

export interface IState {
token: string | null;
}
export const tokenReducer = (
state: IState['token'] = null,
{ type, payload }: AppAction,
): typeof state => {
switch (type) {
case 'LOGIN':
return payload;
default:
return state;
}
};

这很有效。然而,我试着这样改变它:

const initialState: IState = {
token: null
};
export const tokenReducer = (
//state: IState['token'] = null,
state = initialState,
//state: initialState
action: AppAction,
): typeof state => {
switch (type) {
case 'LOGIN':
return action.payload;
default:
return state;
}
};

但是我会出错。如果我按照IDE的建议使用state: typeof initialStatestate = 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)
``
What am I doing wrong? Am I making a syntax error or is it just not allowed to define initialStates like this?

问题可能是:根本没有返回状态。您只是覆盖它或仅返回令牌(而不是作为对象(,这取决于您的负载。我想LOGIN-action将返回一个令牌。因此,正确的减速器如下:

export const tokenReducer = (
state: IState['token'] = initialState,
{ type, payload }: AppAction,
): IState => {
switch (type) {
case 'LOGIN':
return {
...state,
token: payload,
};
default:
return state;
}
};

或者有效载荷包含{token: string}

编辑:好吧,仔细看了第一个tokenReducer之后,我认为它只减少了token,而不是一个对象。因此,一个正确的initialState应该是:

// this equals the `token` in `IState`
const initialState: string | null = null

是的,分配state = initialState,在语法上是正确的。

相关内容

  • 没有找到相关文章

最新更新