簡體   English   中英

使用異步/等待變量反應設置初始 state

[英]react set initial state with async/await variable

我在 Javascript 中使用 async/await 根據用戶的 ip 地址獲取用戶的坐標。 然后我使用這些坐標作為一些 React 組件的初始 state 值。 call fetch 調用有效,但沒有等待。 我想我對 async/await 的使用有問題。 如何確保 fetch 調用在繼續之前返回? 這是我的代碼:

let ip_address_coords
const get_ip_coords = () => {
  try {
    let resp = fetch("https://ip-geolocation.whoisxmlapi.com/api/v1?apiKey=<my_api_key>")
    let data = resp.json()
    return {lng: data.location.lng, lat: data.location.lat}
  } catch (err) {
    console.log(err)
  }
}

(async () => {
  ip_address_coords = await get_ip_coords();
})()

class Application extends React.Component {
  constructor(props) {
    super()
    this.state = {
      lng: ip_address_coords['lng'],
      lat: ip_address_coords['lat']
    }
    ...

我認為問題是你正在使用異步外部 function 你必須處理它孩子 function 我認為。

Use like this because every function have their own context so you have to handle that function individually so you can handle async task it two ways: Use async wait on following method Better way of handling use Promiss on inner function then your async wait may work

const get_ip_coords = async () => {
try{
let resp = await fetch("https://ip-geolocation.whoisxmlapi.com/api/v1?apiKey=<my_api_key>")
let data = resp.json()
   return {lng: data.location.lng, lat: data.location.lat}
 } catch (err) {
    console.log(err)
  }
}

或者

 const get_ip_coords = () => {
    return new Promiss((resolve,reject)=>{
             fetch("https://ip-geolocation.whoisxmlapi.com/api/v1?apiKey= 
               <my_api_key>").then(res=>{
                    let data = resp.json()
                    resolve({lng: data.location.lng, lat: data.location.lat})
                }).catch(err=>{
                      reject(err)
                })
    })
}

您也可以使用回調機制。

我仍然不確定為什么這不像最初寫的那樣工作,但我找到的解決方案是使實際使用坐標的組件的 componentDidMount 方法異步。

它看起來像這樣:

  get_ip_coords = () => {
    return new Promise(async (resolve, reject) => {
      const resp = await fetch("https://ip-geolocation.whoisxmlapi.com/api/v1?apiKey=<my_api_key>")
      const data = await resp.json()
      resolve([data.location.lng, data.location.lat])
    })
  }
  
  componentDidMount = async () => {
    const map = new mapboxgl.Map({
      center: await this.get_ip_coords(),
      ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM