如何解决反应本机上下文和不建议使用的超级用法
我离开本机编程已经有一个星期了,当我回来时,经过一些VSCode更新后,我注意到我在类构造函数中的许多super(props)
调用现在都标记为已弃用。原因似乎是一些旧的上下文API问题,在以下链接中对此问题进行了解释:React Native Legacy Context
我从链接中了解了一些影响上下文使用的问题。但是,对于是否需要拨打super()
,super(props)
或根本不打电话,我现在有些困惑。我以前的理解是,编写扩展基类的类始终需要调用super()
。如果基类构造函数还使用构造函数中接收到的任何props,则还需要将super(props)
传递给props。
在我的代码中,如果需要有状态组件,我几乎总是扩展React.Component
。我很少需要在this.props
中使用constructor()
,如果这样做了,我只会用它来设置初始状态对象,然后再处理生命周期方法的更改。以下是我大多数班级组件的外观:
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。
解决方法
进一步研究之后,看来我对super()
和super(props)
的使用是正确的。我将super(props)
标记为已弃用时遇到的问题是由于React的TS定义中的错误弃用标记所致。
应该被标记为不赞成使用的是super super(props,context)
的重载形式,它采用了React的遗留上下文API所使用的context
道具。
此问题在Microsoft的TypeScript github页面上的(当前为打开状态)问题上得到了更好的描述和讨论:https://github.com/microsoft/TypeScript/issues/40511
在问题解决之前,可以安全地忽略弃用警告。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。