Flow(React Native)给出了使用'this.state'的错误

Mic*_*all 39 reactjs flowtype react-native

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

object literal:此类型与undefined不兼容.您是否忘记声明State标识符的类型参数Component?:

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

class ExpandingCell extends Component {
    constructor(props) {
    super(props);
    this.state = {
        isExpanded: false
    };
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激=)

小智 59

您需要为state属性定义一个类型才能使用它.

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


Der*_*ike 25

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


1.创建一个typeforthis.state

type State = { width: number, height: number }
Run Code Online (Sandbox Code Playgroud)

2.用它初始化你的组件type

export default class MyComponent extends Component<Props, State> { ... }
Run Code Online (Sandbox Code Playgroud)

3.现在您可以设置this.state没有任何流量错误

  constructor(props: any) {
    super(props)
    this.state = { width: 0, height: 0 }
  }
Run Code Online (Sandbox Code Playgroud)

这是一个更完整的示例,this.stateonLayout调用时会更新组件的宽度和高度.

// @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',
  },
})
Run Code Online (Sandbox Code Playgroud)