永久更新响应循环componentDidUpdate

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

根据文档:

[当组件更新后,以此为契机在DOM上进行操作。只要您将当前道具与以前的道具进行比较,这也是执行网络请求的好地方(例如,如果道具没有更改,则可能不需要网络请求)。

componentDidUpdate(prevProps) {
  // Typical usage (don't forget to compare props):
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}

现在我的方法如下:

componentDidUpdate(prevProps) {
    console.log("Fitting update");
    this.getDataBasedOnMessurements();
}

getDataBasedOnMessurements() {
    fetch(process.env.REACT_APP_API_URL + 'configurator/getFittingData', {
        method: 'PUT',
        body: JSON.stringify(this.props.messurements)
    }).then((response) => {
        return response.json();
    }).then((myJson) => {
        this.setState({data: myJson.fittingExtra})
    });
};

问题在于,由于状态正在更新,因此ComponentDidUpdate现在处于永远循环中enter image description here

因此,在更新组件上的道具时,调用API和更新状态的正确方法是什么?

javascript reactjs
1个回答
0
投票

在此代码中,每次更新道具都会调用getDataBasedOnMessurements函数,因为componentDidUpdate代码中没有条件。您必须比较道具以获取要触发api调用的特定情况。


0
投票

调用API的正确位置在componentDidMount()中,而更新状态在componentDidUpdate中。

但是正如我所看到的,您没有使用任何reducer或调度任何函数。您在获得响应后直接设置数据,而不是更新道具。因此,您可以删除componentDidUpdate()方法,而只需在componentDidMount()]中调用API

请检查此代码,

componentDidMount() {
    this.getDataBasedOnMessurements();
}

getDataBasedOnMessurements() {
    fetch(process.env.REACT_APP_API_URL + 'configurator/getFittingData', {
        method: 'PUT',
        body: JSON.stringify(this.props.messurements)
    }).then((response) => {
        return response.json();
    }).then((myJson) => {
        this.setState({data: myJson.fittingExtra})
    });
};
© www.soinside.com 2019 - 2024. All rights reserved.