React Native 上下文和不推荐使用的"super"用法

4

我离开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。

1个回答

6
进一步研究后,我发现我对super()super(props)的使用知识是正确的。我遇到的super(props)被标记为已弃用的问题是由于React的TS定义中存在错误的弃用标记所致。
应该标记为已弃用的是重载形式的super,即super(props, context),它接受一个context属性,该属性由React的传统上下文API使用。
这个问题在Microsoft的TypeScript github页面上有更详细的描述和讨论: https://github.com/microsoft/TypeScript/issues/40511 在问题得到解决之前,可以安全地忽略弃用警告。

1
似乎一份补丁即将到来。 - weeix

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接