gpt4 book ai didi

javascript - react 更新永远循环 componentDidUpdate

转载 作者:行者123 更新时间:2023-11-28 16:45:40 25 4
gpt4 key购买 nike

根据文档:

Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).

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

那么当组件上的 props 更新时,调用 API 并更新状态的正确方法是什么?

最佳答案

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

但正如我所看到的,您没有使用任何 reducer 或分派(dispatch)任何函数。您在收到响应后直接设置数据,而不是更新 props。因此,您可以删除 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})
});
};

关于javascript - react 更新永远循环 componentDidUpdate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60590097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com