reactjs - 将 React Memo 与 Flow 结合使用的正确方法是什么?

标签 reactjs flowtype

这行代码

export default memo(LoadingOverlay);

给出流量错误

Missing type annotation for `P`. `P` is a type parameter declared in  function type [1] and was implicitly instantiated at  call of `memo` [2].Flow(InferError)

还有这一行

export default memo<TProps>(LoadingOverlay);

给出编译时错误。 React memoflow 的正确用法是什么?

编辑:

这是完整的文件示例

// @flow

// React modules
import React, { memo } from 'react';

// Material UI components
import Checkbox from '@material-ui/core/Checkbox';
import FormControlLabel from '@material-ui/core/FormControlLabel';

// Utils and defaults
import './checkbox.scss';

type TProps = {
  value: string;
  label: string;
  checked: boolean;
  disabled?: boolean;
  onChange: Function;
};

/*
 * Presentational component with following props:
 *  value: String, value as a name of checkbox
 *  label: String, checkbox label
 *  checked: Boolean, checkbox state
 *  disabled: Boolean, checkbox availability state
 */
const Checkbox = (props: TProps) => {
  console.log('RENDER CHECKBOX');
  const {
    value,
    label,
    checked,
    disabled
  } = props;
  const { onChange } = props;

  return (
    <FormControlLabel
      control={
        <Checkbox
          checked={checked}
          onChange={onChange(value)}
          value={value}
          disabled={disabled}
          color="primary"
        />
      }
      label={label}
    />
  );
};

Checkbox.defaultProps = {
  disabled: false,
};

export default memo<TProps>(Checkbox);

最佳答案

我也遇到了同样的问题。 问题不在于 Flow,而在于 Babel。

带有 Flow 的 React.memo

你说得对。正确的做法确实是:

export default memo<Props>(MyComponent);

编译问题

有两种方法可以解决这个问题。

1。简单:在顶部添加流注释

//@flow 添加到文件顶部。该错误来自 Babel,需要在那里进行注释。即使您可能在 .flowconfig 中有 all=true (并且 Flow 工作完美),您也需要这样做。

在使用create-react-app并且不想弹出时很有用。

2。配置 Babel

为 Flow 添加 Babel 预设,并在 .babelrc 中指定 "all": true 选项:

{   
  "presets": [
    ["@babel/preset-flow", {
      "all": true
    }]
  ]
}

但是,这需要任何人使用create-react-app弹出(或者可能使用react-app-rewired,但我没有经验与此。)

here 中提到了此解决方案(感谢 @fl0shizzle mentioning 它)以及关于 create-react-app 解决方案的讨论请查看 here .

关于reactjs - 将 React Memo 与 Flow 结合使用的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53863768/

相关文章:

javascript - 为什么状态始终为 0,即使使用 useCallback 后也是如此

javascript - React : In state, 我如何更新某个索引处的嵌套对象?

javascript - 缺少 `T` 的类型注释

javascript - 刷新选项卡而不是 ReactJs Ajax 页面

javascript - 可以有条件地导入 NodeJS/React 中的模块吗?

javascript - 在 ReactJs 中使用 NodeJS API 登录失败

javascript - 如何使用 Jest 模拟 HTML5 文件对象

javascript - 混合正常和 Flow -'type' 导入

javascript - 流联合类型在递归调用中不起作用

javascript - 如何纠正流量警告: destructuring (Missing annotation)