在 React 组件中循环 AJAX 请求
Looping AJAX request in a React component
这是我的问题。我正在尝试通过 React 应用程序中的 AJAX 调用(使用 Axios)从 public API 获取一些数据(latitude/longitude)。
用户填写地址和邮政编码输入,它们的值作为参数传递到 AJAX fetchCoordinates() 请求函数中,一旦它返回一些数据,它应该更新 latitude/longitude 状态与第一个结果的坐标。
用户可以更新地址和邮政编码输入,应用程序应随之更新坐标状态。
这是有问题的方法代码:
componentDidUpdate(prevState) {
fetchCoordinates(this.state.address, this.state.postcode)
.then((data) => {
if (typeof(data) === "object" && data.features.length) {
this.setState(function() {
return {
latitude: data.features[0].geometry.coordinates[1],
longitude: data.features[0].geometry.coordinates[0]
}
});
}
})
}
实际上,我可以取回坐标,甚至可以将它们渲染到屏幕上,但是一旦我取回坐标,AJAX 请求就无法停止循环,一次又一次...
我是 React 初学者,但这看起来很可疑!
如果有人有想法,那就太好了。提前感谢您的帮助。
西尔维尔
this.setState
不应调用函数
this.setState(function() { // remove the function piece here
return {
latitude: data.features[0].geometry.coordinates[1],
longitude: data.features[0].geometry.coordinates[0]
}
})
应该阅读
this.setState({
latitude: data.features[0].geometry.coordinates[1],
longitude: data.features[0].geometry.coordinates[0]
})
如前所述 - 您应该将此代码放在 ComponentDidMount
或 ComponentWillMount
中 - 而不是 ComponentDidUpdate
这是我的问题。我正在尝试通过 React 应用程序中的 AJAX 调用(使用 Axios)从 public API 获取一些数据(latitude/longitude)。
用户填写地址和邮政编码输入,它们的值作为参数传递到 AJAX fetchCoordinates() 请求函数中,一旦它返回一些数据,它应该更新 latitude/longitude 状态与第一个结果的坐标。
用户可以更新地址和邮政编码输入,应用程序应随之更新坐标状态。
这是有问题的方法代码:
componentDidUpdate(prevState) {
fetchCoordinates(this.state.address, this.state.postcode)
.then((data) => {
if (typeof(data) === "object" && data.features.length) {
this.setState(function() {
return {
latitude: data.features[0].geometry.coordinates[1],
longitude: data.features[0].geometry.coordinates[0]
}
});
}
})
}
实际上,我可以取回坐标,甚至可以将它们渲染到屏幕上,但是一旦我取回坐标,AJAX 请求就无法停止循环,一次又一次...
我是 React 初学者,但这看起来很可疑!
如果有人有想法,那就太好了。提前感谢您的帮助。
西尔维尔
this.setState
不应调用函数
this.setState(function() { // remove the function piece here
return {
latitude: data.features[0].geometry.coordinates[1],
longitude: data.features[0].geometry.coordinates[0]
}
})
应该阅读
this.setState({
latitude: data.features[0].geometry.coordinates[1],
longitude: data.features[0].geometry.coordinates[0]
})
如前所述 - 您应该将此代码放在 ComponentDidMount
或 ComponentWillMount
中 - 而不是 ComponentDidUpdate