Flow (React Native) 给我错误使用 'this.state'

Flow (React Native) is giving me errors for using 'this.state'

每当我尝试在我的代码中使用 this.state 时,Flow 都会给我以下错误:

object literal: This type is incompatible with undefined. Did you forget to declare type parameter State of identifier Component?:

这是有问题的代码(尽管它也发生在其他地方):

class ExpandingCell extends Component {
    constructor(props) {
    super(props);
    this.state = {
        isExpanded: false
    };
}

任何帮助将不胜感激 =)

您需要为状态定义类型 属性 才能使用它。

class ComponentA extends Component {
    state: {
        isExpanded: Boolean
    };
    constructor(props) {
        super(props);
        this.state = {
            isExpanded: false
        };
    }
}

删除你代码中的/* @flow */ flite top

如果您正在使用 flow 并希望在组件的 constructor 中设置 this.state:


1.this.state

创建一个 type
type State = { width: number, height: number }

2.type

初始化你的组件
export default class MyComponent extends Component<Props, State> { ... }

3. 现在您可以设置 this.state 而不会出现任何 flow 错误

  constructor(props: any) {
    super(props)
    this.state = { width: 0, height: 0 }
  }

这是一个更完整的示例,它在调用 onLayout 时使用组件的宽度和高度更新 this.state

// @flow

import React, {Component} from 'react'
import {View} from 'react-native'

type Props = {
  someNumber: number,
  someBool: boolean,
  someFxn: () => any,
}

type State = {
  width: number,
  height: number,
}

export default class MyComponent extends Component<Props, State> {

  constructor(props: any) {
    super(props)

    this.state = {
      width: 0,
      height: 0,
    }
  }

  render() {

    const onLayout = (event) => {
      const {x, y, width, height} = event.nativeEvent.layout
      this.setState({
        ...this.state,
        width: width,
        width: height,
      })
    }

    return (
      <View style={styles.container} onLayout={onLayout}>

        ...

      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
  },
})

您可以忽略流类型:any的状态,但不建议这样做。当你的状态变得更大更复杂时,你会迷失方向。

class ExpandingCell extends Component {

    state: any;

    constructor(props) {
        super(props);
        this.state = {
            isExpanded: false
        };
    }
}