【问题标题】:Looping AJAX request in a React component在 React 组件中循环 AJAX 请求
【发布时间】:2017-08-12 20:15:49
【问题描述】:

这是我的问题。我正在尝试通过 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 初学者,但这看起来很可疑!

如果有人有想法,那就太好了。提前谢谢您的帮助。

银子

【问题讨论】:

    标签: ajax reactjs axios


    【解决方案1】:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-24
      • 2020-11-01
      • 2017-08-08
      • 2021-03-15
      • 2011-11-06
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多