You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中经纬度setState后fetch请求取值为undefined的问题

问题原因
  • 异步执行逻辑错误:Geolocation.getCurrentPosition 是异步非阻塞API,你把fetch请求和定位API同步写在componentDidMount中时,定位的成功回调还没被触发,latitude和longitude两个state还没被赋值,读取自然为undefined。
  • setState异步特性:React的setState方法本身是异步操作,调用后不会立刻更新this.state的值,就算你在定位回调里刚执行完setState就立刻读state,也不一定能拿到最新值,需要借助setState的第二个回调参数处理后续逻辑。
  • 权限判断逻辑错误:hasLocationPermission是返回Promise的异步函数,你直接写if (hasLocationPermission)是判断函数本身是否为真值,永远返回true,根本没有用到权限校验的实际结果。
  • 语法错误:你给出的代码中fetch的第二个.then方法结束后缺少闭合括号,会直接报语法错误。
修复方案

正确的执行顺序应该是:校验权限 → 校验通过后发起定位 → 定位成功拿到经纬度后再发起天气接口请求,修复后代码如下:

async componentDidMount() {
  // 先等待权限校验完成
  const hasPermission = await hasLocationPermission();
  this.setState({_isLocationEnabled: hasPermission});
  
  if (!hasPermission) {
    // 无权限的处理逻辑,比如弹窗提示用户
    this.setState({ isLoading: false });
    return;
  }

  // 有权限再调用定位接口
  Geolocation.getCurrentPosition(
    position => {
      const { latitude, longitude } = position.coords;
      // 拿到经纬度后直接用变量的值发起请求,无需等待setState更新
      this.fetchWeatherData(latitude, longitude);
      // 更新state
      this.setState({
        latitude,
        longitude
      }, () => {
        // 如果需要读取更新后的state,要在setState的回调中操作
        console.log(this.state.latitude, this.state.longitude);
      });
    },
    error => {
      console.log(error.code, error.message);
      this.setState({ isLoading: false });
    },
    {
      enableHighAccuracy: true,
      timeout: 15000,
      maximumAge: 10000,
    }
  );
}

// 单独封装天气请求方法
fetchWeatherData = (lat, lon) => {
  const fetch = require('node-fetch');
  console.log('请求参数:', lat, lon);
  fetch(
    `https://api.weatherapi.com/v1/forecast.json?q=${lat},${lon}`,
    {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    }
  )
  .then(response => response.json())
  .then(responseJson => {
    console.log(responseJson);
    this.setState({
      isLoading: false,
      dataSource: responseJson,
    });
  })
  .catch(error => {
    console.error(error);
    this.setState({ isLoading: false });
  });
}

内容的提问来源于stack exchange,提问作者CodeLover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 06:48:02