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

后端 未结 4 1627
死守一世寂寞
死守一世寂寞 2021-01-01 08:34

Flow is giving me the following error whenever I try to use this.state in my code:

object literal: This type is incompatible with un

相关标签:
4条回答
  • 2021-01-01 09:14

    You can ignore the state with flow type :any, but this is not recommended. You will get lost when your state get bigger and more complicated.

    class ExpandingCell extends Component {
    
        state: any;
    
        constructor(props) {
            super(props);
            this.state = {
                isExpanded: false
            };
        }
    }
    
    0 讨论(0)
  • 2021-01-01 09:21

    You need to define a type for the state property in order to use it.

    class ComponentA extends Component {
        state: {
            isExpanded: Boolean
        };
        constructor(props) {
            super(props);
            this.state = {
                isExpanded: false
            };
        }
    }
    
    0 讨论(0)
  • 2021-01-01 09:29

    delete the /* @flow */ in you code flite top

    0 讨论(0)
  • 2021-01-01 09:33

    If you're using flow and want to set this.state in your component's constructor:


    1. Create a type for this.state

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

    2. Initialize your component with that type

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

    3. Now you can set this.state without any flow errors

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

    Here's a more complete example that updates this.state with the width and height of the component when onLayout is called.

    // @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',
      },
    })
    
    0 讨论(0)
提交回复
热议问题