繁体   English   中英

无法更新 Reactjs 中的 setState

[英]Unable to update the setState in Reactjs

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

谁能帮我找出我的代码中的错误?

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

结果控制台details: {address: "Melbourne", latitude: "", longitude: ""}

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

如果你问为什么在控制台中你得到

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

这是因为axios调用是异步的,console.log 在 axios 完成之前触发,即使你把它放在axios调用之后。 是的,这就是 Javascript 的做法。

要真正知道您的 state 是否正在更新,请将console.log放在 this.setState 之后, thenthis.setState

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM