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

时间:2019-11-28 13:53:27

标签: javascript reactjs native

我正在使用React Native,并尝试理解一些示例。

我有问题

我正在尝试通过纬度进行传递,但是我遇到一个问题,谁说我的“纬度”不存在

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 = [];

您能帮我吗,谢谢:)

3 个答案:

答案 0 :(得分:2)

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

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

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
}

答案 1 :(得分:1)

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

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

答案 2 :(得分:-1)

尝试像这样使用提取:

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