React native api fetch don’t get parameters



我的反应原生代码有问题,我正在尝试从 api url 获取数据,并且进行了多次调用。所以我得到了数据,但我的最后一次调用不起作用,我需要以前调用的数据并将其传递给我的方法,但这不起作用。该方法由带有 onpress 的按钮启动,如果我按一个参数为空,但如果我第二次按下,我会得到参数。

这是我的代码:

_getResults() {
this.setState({ isLoading: true })
defaultStops().then(data => {
  this.setState({ 
    stops: data.data,
    isLoading : false
   })
})
getDepStop(this.depStop).then(data => {
  this.setState({ 
    depStop: data.data[0].name,
    depStopId: data.data[0].id,
    isLoading : false
   })
})
getArrStop(this.arrStop, this.state.depStopId).then(data => {
  this.setState({ 
    arrStop: data.data[0].name,
    arrStopId: data.data[0].id,
    isLoading : false
   })
})
getCompany(this.state.depStopId, this.state.depStop, this.state.arrStopId, this.state.arrStop, this.date).then(data => {
  this.setState({ 
    company: data,
    isLoading : false
   })
})
}

它的getCompany方法没有得到所有以前的方法都在工作的参数。

这是我的 api 调用:

export function defaultStops () {
const url = 'https://www.APIURL.com/api/stops/departure?lang=fr'
return fetch(url)
.then((response) => response.json())
.catch((error) => console.error(error))
}
export function getDepStop (text) {
const url = 'https://www.APIURL.com/api/stops/departure?lang=fr&term=' + text + '&q=' + text
return fetch(url)
.then((response) => response.json())
.catch((error) => console.error(error))
}
export function getArrStop (text, depStopId) {
const url = 'https://www.APIURL.com/api/stops/arrival?lang=fr&q=' + text + '&stopId=' + depStopId
return fetch(url)
.then((response) => response.json())
.catch((error) => console.error(error))
}
export function getCompany (depStopId, depStopName, arrStopId, arrStopName, date) {
const url = 'https://www.APIURL.com/api/routes?id=1&depStopId='+depStopId+'&depStopName='+depStopName+'&arrStopId='+arrStopId+'&arrStopName='+arrStopName+'&dateFrom='+date+'&type=bus&currency=EUR'
return fetch(url)
.then((response) => response)
.catch((error) => console.error(error))
}
export function getTicket (depStopId, arrStopId, stopExtDep, stopExtArr, date, companyId) {
const url = 'https://APIURL/api/prices?companyId='+ companyId +'&stopExtDep='+ stopExtDep +'&stopExtArr='+ stopExtArr +'&stopIdDep='+ depStopId +'&stopIdArr='+ arrStopId +'&dateFrom='+ date +'&dateTo=&currency=EUR&k=cbapp'
return fetch(url)
.then((response) => response.json())
.catch((error) => console.error(error))
}

有人可以帮我吗?

好的,所以解决方案是在我的setState之后使用回调:

getArrStop(this.arrStop, this.state.depStopId).then(data => {
  this.setState({ 
    arrStop: data.data[0].name,
    arrStopId: data.data[0].id,
    isLoading : false
   },function(){getCompany(this.state.depStopId, this.state.depStop, this.state.arrStopId, this.state.arrStop, this.date).then(data => {
    this.setState({ 
      company: data,
      isLoading : false
     })
  })})
})

最新更新