繁体   English   中英

如何在获取请求中传递变量

[英]How can I pass variable in my fetch request

我正在使用本机反应并尝试理解一些示例。

我有问题

我试图在我的抓取中传递纬度,但我遇到了一个问题,他说我的“纬度”不存在

class App extends React.Component {
constructor() {
super();
this.state = {
  region: {
    latitude: LATITUDE,
      longitude: LONGITUDE,
      latitudeDelta: LATITUDE_DELTA,
      longitudeDelta: LONGITUDE_DELTA,
  },
  markers: [],
  loaded: false
}

}

componentDidMount() {
navigator.geolocation.getCurrentPosition(
  (position) => {
    console.log(position);
    this.setState({
      region: {
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA,
      }
    });
  },
  (error) => this.setState({ error: error.message }),
  { enableHighAccuracy: false, timeout: 200000, maximumAge: 1000 },
  );
  this.getLocations()
}


getLocations(){
  return fetch('https://***&geofilter.distance='+latitude+'%2C2.3883402698750875%2C2000') //here
  .then(response => response.json())
  .then(responseData =>{
    var markers = [];

你能帮帮我吗,谢谢:)

getLocations中,您尝试使用latitude变量,但那里没有范围。 您可能想要this.state.region.latitude

但是,如果您尝试使用this.state.region.latitude ,则需要将调用移至componentDidMount中的getLocations ,以便它位于状态更改完成处理程序中:

componentDidMount() {
  navigator.geolocation.getCurrentPosition(
    (position) => {
      console.log(position);
      this.setState({
        region: {
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          latitudeDelta: LATITUDE_DELTA,
          longitudeDelta: LONGITUDE_DELTA,
        }
      },
      () => {                   // ***
        this.getLocations();    // ***
      });                       // ***
    },
    (error) => this.setState({ error: error.message }),
    { enableHighAccuracy: false, timeout: 200000, maximumAge: 1000 },
  );
  // *** Not here
}

您正在将纬度存储在状态中,因此您需要将其称为this.state.region.latitude

return fetch('https://***&geofilter.distance='+this.state.region.latitude+'%2C2.3883402698750875%2C2000')

尝试像这样使用您的提取:

return fetch('https://***&geofilter.distance='+this.state.region.latitude+'%2C2.3883402698750875%2C2000')

暂无
暂无

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

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