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

后端 未结 4 1645
死守一世寂寞
死守一世寂寞 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: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 { ... }
    

    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 {
    
      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 (
          
    
            ...
    
          
        )
      }
    }
    
    const styles = StyleSheet.create({
      container: {
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
      },
    })
    

提交回复
热议问题