将 React Memo 与 Flow 一起使用的正确方法是什么?

What is the proper way to use React Memo with Flow?

这行代码

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,因此必须将 all=true 添加到我的预设配置中。

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

React.memo 流量

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

export default memo<Props>(MyComponent);

编译问题

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

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

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

在使用create-react-app而不想eject时有用。

2。配置 Babel

为 Flow 添加 Babel 预设,并为您的 .babelrc:

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

但是,这需要任何人使用 create-react-appeject(或者可能使用 react-app-rewired,但我没有这方面的经验。 )

here (thanks @fl0shizzle for it) and for discussion about create-react-app solution look on here.

中提到了此解决方案