【发布时间】:2019-09-29 06:25:43
【问题描述】:
我正在使用 Context API 和 React Hooks 构建一个 React 应用程序。我正在尝试遵循最佳实践。为此,我使用Flow 并尝试遵守其警告。
我有一种情况,一旦用户登录,我想在我建立的SessionContext 中存储有关该用户的一些数据。鉴于现在只有 3 条数据并且它们都是原始的,我认为只有一个 Reducer Action 是有意义的:
export const sessionReducer = (state: SessionState, action: SessionAction) => {
switch (action.type) {
case UPDATE_SESSION_PROP: {
return {
...state,
[action.propName]: action.payload
};
}
default: {
return state;
}
}
}
以下是我为说明这 3 种数据类型而创建的操作类型:
export type UserEmailAction = {type: 'UPDATE_SESSION_PROP',
propName: 'currentUserEmail',
payload: string};
export type UserAccessLevelAction = {type: 'UPDATE_SESSION_PROP',
propName: 'currentUserAccessLevel',
payload: number};
export type CurrentCompanyNameAction = {type: 'UPDATE_SESSION_PROP',
propName: 'currentCompanyName',
payload: string};
在我的SessionContext中,我将这3种Action类型组合如下,然后从中定义一个Dispatch类型:
export type SessionAction =
| UserEmailAction
| UserAccessLevelAction
| CurrentCompanyNameAction;
type Dispatch = (action: SessionAction) => void;
在此代码中,sessionReducer 之上有 4 条警告消息:
const [state: SessionState, dispatch: Dispatch] = useReducer(sessionReducer, defaultState);
消息类似于:“不能调用 useReducer 与 sessionReducer 绑定到 reducer 因为数字 [1] 与返回值的属性 currentCompanyName 中的字符串 [2] 不兼容。”
我是否错误地定义了 Action 类型,或者 Flow 只是不够智能来区分这 3 种模式?顺便说一句,这种方法在运行时似乎运行良好。
【问题讨论】:
标签: react-hooks flowtype react-context