reactjs 为什么总是undefined(当请求没有参数和地理位置搜索(lat和zh)时,

rvpgvaaj  于 11个月前  发布在  React
关注(0)|答案(1)|浏览(156)
export const fetchIataViaGeo = createAsyncThunk(
  'iata/fetchIataViaGeo',

  async () => {
    const error = () => {
      alert('Sorry, we could not find your location. Please enter manually.');
    };
    const succuess = async (position) => {
      const lat = position.coords.latitude;
      const lng = position.coords.longitude;
      const res = await axios.get(
        `https://airlabs.co/api/v9/nearby?lat=${lat}&lng=${lng}&distance=45&api_key=...`
      );
      console.log(res.data.response.airports);
      return await res.data.response.airports;
    };
    navigator.geolocation.getCurrentPosition(succuess, error);
  }
);

字符串
这可能是因为我把它还错了地方,但我不知道哪里需要它。当我尝试它没有地理定位请求,它工作得很好

xsuvu9jc

xsuvu9jc1#

payloadCreator回调函数中没有返回任何内容(createAsyncThunk的第二个参数是createAsyncThunk的函数:请参阅以下文档:https://redux-toolkit.js.org/api/createAsyncThunk#overview
但是,您不能简单地返回navigator.geolocation.getCurrentPosition的结果,因为它总是返回undefined:https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition#return_value
您需要的是返回Promise的getCurrentPosition。请参见https://whatwebcando.today/articles/use-geolocation-api-promises/
你会想要看起来像这样的东西:

function promiseGetCurrentPosition() {
    return new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject);
    });
}

字符串
你可以使用如下:

export const fetchIataViaGeo = createAsyncThunk(
    'iata/fetchIataViaGeo',
    async () => {
        const position = await promiseGetCurrentPosition();
        const latitude = position.coords.latitude;
        const response = await axios.get(`http://example.com/api?lat=${latitude);
        // note that I don't use await here, since I already awaited response
        return response.data.airports; 
    }
);

相关问题