我是新手。在我的程序中,每次我在componentDidUpdate()中设置ajax请求并设置新状态时,就会创建一个无限循环。还有一件事“是在componentDidmount()和componentDidUpdate()中进行Ajax调用的正确方法吗?”
这是我的Handler函数
componentDidUpdate() {
this.getUnitsHandler();
}
componentDidMount() {
this.getUnitsHandler();
}
getUnitsHandler = () => {
Axios.get('http://localhost:4000/getUnit').then(response => {
this.setState({
units: response.data
})
}).catch(err => {
console.log(err);
})
}
此处停止无限循环的逻辑应该是什么?
答案 0 :(得分:2)
通常,您需要检查道具是否有变化,然后进行更新:
componentDidUpdate(prevProps) {
if (prevProps[someKey] !== this.props[someKey]) {
this.getUnitsHandler();
}
}
但是,在这种情况下,您没有使用任何实例变量来进行api调用,因此根本不需要使用componentDidUpdate
。
将api调用添加到componentDidMount
将在组件安装后发出请求,查看代码应足以满足您的目的。
有用的链接:
答案 1 :(得分:0)
最好在componentDidMount()方法中编写ajax调用,因为它在dom渲染后执行,仅在加载组件时执行一次,但是如果您尝试更新组件,则componentDidUpdate将在每次执行时执行更新dom的时间。 因此,进行ajax调用的最佳方法是componentDidMount方法。 来自react doc componentDidMount
答案 2 :(得分:0)
永远不要在componentDidUpdate中执行setState,因为setState会再次触发该确切方法。您到底想实现什么?组件安装后是否会调用一个API?如果是这样,请改为在componentDidMount中使用它。
答案 3 :(得分:0)
您可以在componentDidUpdate()中立即调用setState(),但请注意,必须将其包装在这样的条件下,
componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}
否则将导致无限循环。这也将导致额外的重新渲染,这虽然对用户不可见,但会影响组件的性能。如果您要“镜像”来自上方的道具的某些状态,请考虑直接使用道具。
如果仅使用状态,则可以从componentDidUpdate回调中捕获以前的状态。