【问题标题】:What is the proper way to use React Memo with Flow?将 React Memo 与 Flow 一起使用的正确方法是什么?
【发布时间】:2019-05-20 16:27:05
【问题描述】:

这行代码

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);

【问题讨论】:

  • 最后一个应该没问题,你有什么编译错误?
  • Uncaught ReferenceError: TProps is not defined babel 好像没有去掉这部分。
  • 你能说明你是如何定义TProps的吗?更新问题
  • @Alex 当然,你可以看看。
  • 我也有这个问题。似乎@babel/preset-flow 还不支持这种语法 >_>

标签: reactjs flowtype


【解决方案1】:

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

React.memo 与 Flow

你做对了。正确的做法确实是:

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 上提到了此解决方案(感谢@fl0shizzle 提供mentioning 它),有关create-react-app 解决方案的讨论请查看here

【讨论】:

  • 所以它更可能是由某些版本问题引起的。与新版本和项目一样,一切似乎都正常。顺便说一句,添加//@flow 对我不起作用
【解决方案2】:

确保您拥有最新版本的流程。当我更新我的流程版本时,它就可以工作了。我错过了顶部的 // @flow 所以必须将 all=true 添加到我的预设配置中。

【讨论】:

    猜你喜欢
    • 2020-02-08
    • 2018-04-10
    • 2013-01-02
    • 1970-01-01
    • 2020-08-27
    • 2020-07-10
    • 2020-09-29
    • 1970-01-01
    • 2012-05-12
    相关资源
    最近更新 更多