无法在Reactjs中更新setState

时间:2020-05-21 10:43:24

标签: javascript reactjs

我目前正在使用React开发Weather应用程序。我在哪里使用Mapbox API提取给定位置的经度和纬度。我无法更新状态,需要更新给定位置的经度和纬度。

任何人都可以帮助我找出我的代码中的错误吗?

Elements links = table.select("a[href]");
System.out.println(links);

控制台结果 import React, { Component } from 'react' import './Display.css' import Individual from '../../Container/Individual/Individual' import axios from 'axios' class Display extends Component { state ={ details:{ address:'Melbourne', latitude:'', longitude:'' } } componentDidMount(){ const URL = `https://api.mapbox.com/geocoding/v5/mapbox.places/${this.state.details.address}.json?access_token=pk.MYAPI_KEY` axios.get(URL) .then(res=>{ console.log(res.data.features[0].center) this.setState({ latitude:res.data.features[0].center[0], longitude:res.data.features[0].center[1] }) }) console.log(this.state) } render() { return ( <div className='Display'> <Individual location={this.state.details.address} latitude={this.state.details.latitude} longitude={this.state.details.longitude} /> {/* <Individual /> <Individual /> <Individual /> <Individual /> <Individual /> */} </div> ) } } export default Display

谁能告诉我为什么我的状态没有更新?

1 个答案:

答案 0 :(得分:0)

如果您询问为什么要在控制台中获得

details: {address: "Melbourne", latitude: "", longitude: ""}

这是因为 axios 调用是异步,并且console.log是在axios完成之前触发的,即使将其放在 axios 之后>致电。是的,这就是Javascript的方式。

要真正知道您的状态是否正在更新,请将console.log之后的this.setState放在then承诺中

axios.get(URL)
.then(res=>{
  console.log(res.data.features[0].center)
  this.setState({
    latitude:res.data.features[0].center[0],
    longitude:res.data.features[0].center[1]
  })
  console.log(this.state) // it should already updated here
})