Flow (React Native) дает мне ошибки для использования 'this.state'
Поток дает мне следующую ошибку, когда я пытаюсь использовать this.state
в своем коде:
литерал объекта: Этот тип несовместим с undefined. Вы забыли объявить параметр типа State
идентификатора Component
?:
Вот код нарушения (хотя это происходит и в другом месте):
class ExpandingCell extends Component {
constructor(props) {
super(props);
this.state = {
isExpanded: false
};
}
Любая помощь была бы очень признательна =)
Ответы
Ответ 1
Вам необходимо определить тип для свойства состояния, чтобы использовать его.
class ComponentA extends Component {
state: {
isExpanded: Boolean
};
constructor(props) {
super(props);
this.state = {
isExpanded: false
};
}
}
Ответ 2
Если вы используете поток и хотите установить 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',
},
})
Ответ 3
Вы можете игнорировать состояние с типом потока :any
, но это не рекомендуется. Вы потеряетесь, когда ваше состояние станет больше и сложнее.
class ExpandingCell extends Component {
state: any;
constructor(props) {
super(props);
this.state = {
isExpanded: false
};
}
}
Ответ 4
удалите /* @flow */
в вашем коде flite top