这行代码
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 memo
与 flow
的正确用法是什么?
编辑:
这是完整的文件示例
// @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/