如果它们的道具不同,如何流动类型组件道具和getDerivedStateFromProps?

How to flow type component props and getDerivedStateFromProps if their props are different?

我有一个 Component 和他的 props 我还有一个额外的 prop 用于 getDerivedStateFromProps。因此,如果我将 props 设置为额外的一个,它会抛出一个错误,即 prop 未被使用。 如果我在没有额外的 prop 的情况下进行设置,它会抛出一个错误,我无法将 prop 放在组件 props[ 中=31=]:

type Props = {|
  name: string,
|};

type StaticProps = {|
  ...Props,
  surname: string,
|};

type State = {|
  name: string,
  surname: string,
|};

export class Foo extends Component<Props, State> {
  state: State = {
    name: '',
    surname: '',
  };

  static getDerivedStateFromProps(props: StaticProps) {
    return { surname: props.surname };
  }

  render() {
    return (
      <div>
        <div>{this.props.name}</div>
        <div>{this.state.surname}</div>
      </div>
    );
  }
}

使用此流类型会引发错误:Cannot create 'Foo' element because property 'surname' is missing in 'Props' [1] but exists in props [2].Flow(InferError)

如果我设置 Component<StaticProps, State> 它会抛出另一个错误: 'surname' PropType is defined but prop is never usedeslint(react/no-unused-prop-types)

如何正确地进行流式输入?

就像错误告诉您:Props 没有您最初尝试设置的属性 surname。所以你需要用那个属性扩展你的类型:

type Props = {
  name: string,
  surname?: string
};

注意:您使用了两种不同的道具类型:最初使用的 PropsgetDerivedStateFromProps 内部使用的 StaticProps .这在我看来真的没有意义。

编辑: 如果您不需要 Props 中定义的所有属性,您可以使用属性后面的 ? 字符将它们设为可选名字.

我在@BoyWithSilverWings 的帮助下修复了它,他建议在 .eslintrc 中设置 React 版本并且它有效。仅将此添加到 .eslintrc 文件:

"settings": {
  "react": {
    "version": "<your react version>" // 16.8.5
  }
}