我已经离开 React Native 编程一个星期了,当我回来时,在一些 VSCode 更新之后,我注意到我在类构造函数中的许多 super(props)
调用现在都是标记为已弃用。原因似乎是一些遗留的上下文 API 问题,此链接对此进行了解释:React Native Legacy Context
我已经从链接中了解了一些影响上下文使用的问题。但是,我现在对是否需要调用 super()
、super(props)
或者根本不调用感到有点困惑。我以前的理解是,编写一个扩展基类的类,总是需要调用 super()
。如果基类构造函数也使用构造函数中接收到的任何 Prop ,则还需要使用 super(props)
传递 Prop 。
在我的代码中,如果我需要一个有状态的组件,我几乎总是扩展 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>;
}
}
谁能帮我理解 super
在 React Native 环境中的正确用法?我还应该提一下,我使用的是基于 React 16.11 发布的 Expo SDK 38。我不清楚上述弃用是否也会影响此版本的 React/React native。
最佳答案
进一步研究后,我对 super()
和 super(props)
的使用的了解似乎是正确的。我遇到的 super(props)
被标记为已弃用的问题是由于 React 的 TS 定义中的错误弃用标记。
应该标记为已弃用的是 super 的重载形式,super(props, context)
,它采用 React 的遗留上下文 API 使用的 context
prop .
Microsoft 的 TypeScript github 页面上的这个(当前打开的)问题对这个问题进行了更好的描述和讨论:https://github.com/microsoft/TypeScript/issues/40511
在问题得到解决之前,可以安全地忽略弃用警告。
关于reactjs - react native 上下文和弃用的 super 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63883401/