为什么要避免在组件构造函数中产生副作用?

问题描述 投票:0回答:1

我想知道是否有充分的理由不在组件的构造函数中而不是在其componentDidMount钩子中发送请求?我已经看到一些interesting (but a bit incomplete) answers用于:在构造函数中获取数据是否是个好主意?答案引述了文档中的一个有趣的地方:

避免在构造函数中引入任何副作用或订阅。对于这些用例,请改用componentDidMount()。

我的问题是关于这一点的,我很好奇地理解side-effects有什么问题,例如这里在构造函数中发送请求。

也许一个简单的例子将有助于消除关于我的问题和所链接的问题之间的歧义的任何歧义:

构造函数中的发送请求

class SomeComponent extends React.Component {
    constructor(props) {
        this.request = fetch(props.someURL);
    }

    async componentDidMount() {
        const data = await this.request;
        this.setState({'data': data});
    }
}

或在componentDidMount中发送

class SomeComponent extends React.Component {
    async componentDidMount() {
        const data = await fetch(props.someURL);;
        this.setState({'data': data});
    }
}

或者按照链接的问题中的建议,绝对不好的一个问题:在构造函数中获取

class SomeComponent extends React.Component {
    constructor(props) {
        this.data = await fetch(props.someURL);
    }

    async componentDidMount() {
        this.setState({'data': this.data});
    }
}
reactjs react-native asynchronous fetch side-effects
1个回答
-1
投票

React组件的构造函数在挂载之前被调用。在为React.Component子类实现构造函数时,应在其他任何语句之前调用super(props)。否则,this.props将在构造函数中未定义,这可能会导致错误。

通常,在React构造函数中仅用于两个目的:

  1. 通过将对象分配给this.state来初始化本地状态。
  2. 将事件处理程序方法绑定到实例。
© www.soinside.com 2019 - 2024. All rights reserved.