【问题标题】:Flow + Redux: Error with redux default actions and strongly typed actionsFlow + Redux:redux 默认操作和强类型操作出错
【发布时间】:2017-04-07 21:37:49
【问题描述】:

按照 Flow 文档 (https://flow.org/en/docs/frameworks/redux/) 中的建议,我正在尝试使用流不相交联合来强类型化 redux 操作对象,但现在遇到了流引发错误处理默认 redux 操作 (@@redux/INIT, @@redux/PROBE_UNKNOWN_ACTION 等)。

此代码的示例是:

// Constant action type strings
export const INIT_STORIES: 'INIT_STORIES' = 'INIT_STORIES';
export const UPDATE_STORY: 'UPDATE_STORY' = 'UPDATE_STORY';

// Strongly typed action objects
export type InitAction = {
  type: typeof INIT_STORIES, stories: Array<Story>
};
export type UpdateAction = {
  type: typeof UPDATE_STORY, storyIndex: number, story: Story
};

// Disjoint union wrapper
export type ActionType = 
| InitAction
| UpdateAction;

//reducer
export default function storiesReducer(
  stories: Array<Story> = [],
  action: ActionType
): Array<Story> {
  // Error is thrown at function invocation, prior to the first inner line of function
  // Uncaught TypeError: [tcomb] Invalid value {"type": "@@redux/INIT"
  console.log(action);
  ...
}

我只能在网上找到 1 个针对此问题的问题/解决方案,它使用更复杂的流程运行时来解决问题。 (https://github.com/codemix/flow-runtime/issues/80)

我觉得作为将 Redux 与 Flow 集成的推荐语法,应该有比?我尝试将函数参数action 的类型与具有未定义字符串类型的对象(即{ type: string })设置为不相交的联合,但这会在减速器内部引发类型错误,因为它无法确定是什么action 对象是不相交联合对象的分支。

【问题讨论】:

  • 你使用的是flow-typed中提供的libdef吗?
  • @LewisChung 不,我不知道,我不知道有现成的库。我一定会调查的。我想我可以将我的动作定义作为不相交的联合应用到flow-typed libdef 中的基本 redux 动作类型之上?
  • 由于您使用的是 tcomb,看来您仍然会遇到同样的问题。我问您是否使用了流类型,因为看起来可以修改此处存在的流类型定义:github.com/flowtype/flow-typed/blob/master/definitions/npm/… 以自动考虑默认流操作,因此您不会得到 {"type": "@ @redux/INIT"}。话虽如此,我不太确定 tcomb 是如何实际使用流类型的 libdef。
  • $Subtype&lt;string&gt; 键入可以防止错误出现,并且仍然允许流运行时读取 switch/case 中的适当分支,所以我认为它是一个足够好的解决方案!谢谢指点。

标签: reactjs redux flowtype


【解决方案1】:

最简单的解决方案,不为redux导入完整的flow-typed包,是在ActionType不相交联合类型中添加一个不相交联合{ type: $Subtype&lt;string&gt; },如下所示:

// Disjoint union wrapper
export type ActionType = 
| InitAction
| UpdateAction
| { type: $Subtype<string> };


//reducer
export default function storiesReducer(
  stories: Array<Story> = [],
  action: ActionType
): Array<Story> {
  console.log(action);
  ...
}

虽然如果操作类型字符串输入错误,这不会引发适当的错误,因为它允许所有字符串类型,它会允许适当的分支来识别 switch/case 块内的不同对象形状。

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 2011-06-29
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多