我离开react native编程已经有一周了,回来后进行了一些VSCode更新后,我注意到我的许多类构造函数中的super(props)
调用现在被标记为过时。原因似乎是一些遗留的上下文API问题,该问题在此链接中解释:React Native Legacy Context
我从该链接中了解了一些影响上下文使用的问题。但是,我现在有点困惑是否需要调用super()
,super(props)
或者根本不需要进行调用。我之前的理解是,编写一个扩展基础类的类始终需要调用super()
。如果基类构造函数还使用了任何在构造函数中接收到的props,则还需要使用super(props)
传递props。
在我的代码中,如果我需要一个具有状态的组件,我几乎总是扩展React.Component
。我很少需要在constructor()
中使用this.props
,如果确实需要,则仅将其用于设置初始状态对象,之后我会使用生命周期方法处理更改。以下是大多数我的类组件的外观:
class ExampleComponent extends React.Component {
constructor(props){
super(props); // super marked as deprecated here
// super(); // super NOT marked as deprecated here
this.state = {
value: this.props.initialValue || 0
};
}
componentDidUpdate = (prevProps, prevState, snapshot) => {
// I would not actually do that, but for the sake of an example
if (this.state.value > 10){
this.setState({ value: 10 });
}
}
increment = () => {
const value = this.state.value + 1;
this.setState({ value });
}
render = () => {
return <View>
<Text>Current value is: { this.state.value }</Text>
<TouchableOpacity onPress={ this.increment }>
<Text>Add one!</Text>
</TouchableOpacity>
</View>;
}
}
有人能帮我理解在React Native环境中super
的正确用法吗?需要注意的是,我正在使用基于React 16.11发布的Expo SDK 38。对我来说不清楚上述弃用是否也影响到这个版本的React / React Native。