在React组件中循环AJAX请求

时间:2017-08-12 20:15:49

标签: ajax reactjs axios

这是我的问题。我试图在React应用程序中通过AJAX调用(使用Axios)从公共API获取一些数据(纬度/经度)。

用户填写地址&邮政编码输入,它们的值在AJAX fetchCoordinates()请求函数中作为参数传递,一旦它返回一些数据,它应该用第一个结果的坐标更新纬度/经度状态。

用户可以更新地址和邮政编码输入,因此应用程序应更新坐标状态。

这是有问题的方法代码:

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初学者,但这看起来很可疑!

如果有人有想法,那就太好了。请事先提供帮助。

Silvère

1 个答案:

答案 0 :(得分:0)

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]
 })

如前所述 - 您应将此代码放入ComponentDidMountComponentWillMount - 而不是ComponentDidUpdate