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
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
};
}
}
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
};
}
}
delete the /* @flow */
in you code flite top
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',
},
})