cri*_*ian 4 super deprecated typescript reactjs react-native
我已经离开 React Native 编程一个星期了,当我回来时,在一些 VSCode 更新之后,我注意到我super(props)在类构造函数中的许多调用现在被标记为已弃用。原因似乎是一些遗留上下文 API 问题,在此链接中对此进行了解释:React Native Legacy Context
我从链接中了解了一些影响上下文使用的问题。不过,我现在有点困惑,我是否需要作出一个电话super(),super(props)或不作在所有的呼叫。我之前的理解是,编写一个扩展基类的类,总是需要调用super(). 如果基类构造函数也使用构造函数中收到的任何道具,super(props)则还需要传递道具。
在我的代码中,React.Component如果我需要一个有状态的组件,我几乎总是会进行扩展。我很少需要this.props在constructor()s中使用,如果需要,我只用它来设置初始状态对象,之后我处理生命周期方法的变化。以下是我的大多数类组件的外观:
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>;
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮助我了解superReact Native 环境中的正确用法吗?我还应该提到我使用的是基于 React 16.11 发布的 Expo SDK 38。我不清楚上面的弃用是否也会影响这个版本的 React/React native。
进一步寻找到在此之后,似乎我使用的知识super()和super(props)正确。我遇到的super(props)被标记为已弃用的问题是由于 React 的 TS 定义中的错误弃用标记造成的。
应该被标记为弃用的是 super, 的重载形式super(props, context),它采用了contextReact 的遗留上下文 API 使用的道具。
这个问题在微软的 TypeScript github 页面上的这个(目前开放的)问题上得到了更好的描述和讨论:https : //github.com/microsoft/TypeScript/issues/40511
在问题得到解决之前,可以安全地忽略弃用警告。
| 归档时间: |
|
| 查看次数: |
1050 次 |
| 最近记录: |