41

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

对象字面量:此类型与 undefined 不兼容。您是否忘记声明State标识符的类型参数Component?:

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

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

任何帮助将不胜感激 =)

4

4 回答 4

60

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

class ComponentA extends Component {
    state: {
        isExpanded: Boolean
    };
    constructor(props) {
        super(props);
        this.state = {
            isExpanded: false
        };
    }
}
于 2016-04-26T11:22:25.007 回答
28

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


1.创建type一个this.state

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

2.用那个初始化你的组件type

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

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

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

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

// @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',
  },
})
于 2017-12-01T23:49:11.770 回答
0

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

class ExpandingCell extends Component {

    state: any;

    constructor(props) {
        super(props);
        this.state = {
            isExpanded: false
        };
    }
}
于 2019-01-18T02:12:10.723 回答
-23

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

于 2016-10-12T05:08:39.940 回答