return AsyncStorage 中的未定义提取

return undefined fetch inside AsyncStorage

我有一个本机反应应用程序,我在其中调用 api 它应该 return JSON 但我只是没有定义。

export function fetchFromAPI() {
  AsyncStorage.getItem('@token', (errToken, token) => {
    let token = null;

    const requestBody = { token: token };

    return fetch(url, {
      method: 'POST',
      body: JSON.stringify(requestBody)
    })
    .then((response) => response.json())
    .then((responseJSON) => {
      console.log(responseJSON); // <-- this shows the correct JSON data
      return responseJSON;
    }).catch((error) => {
      // console.error(error);
    });
  });
}

我也这样称呼该函数:

const apiData = fetchFromAPI();

如果我在 fetch 函数中执行 console.log(),它 return 是 JSON 数据,但如果我对 apiData 执行,它只是未定义.

有谁知道为什么会这样,我做错了什么?

首先,您需要 return getItem 创建的 Promise:

export function fetchFromAPI() {
  return AsyncStorage.getItem('@token', (errToken, token) => {
    let token = null;

    const requestBody = { token: token };

    return fetch(url, {
      method: 'POST',
      body: JSON.stringify(requestBody)
    })
    .then((response) => response.json())
    .then((responseJSON) => {
      console.log(responseJSON); // <-- this shows the correct JSON data
      return Promise.resolve(responseJSON); // <-- this wraps the JSON into a Promise
    }).catch((error) => {
      // console.error(error);
    });
  });
}

然后你需要像这样调用函数:

fetchFromAPI().then(apiData => {...

您可以使用 PromisefetchFromAPI 函数获取响应,例如

export function fetchFromAPI() {
  return new Promise((resolve, reject) => {
    AsyncStorage.getItem('@token', (errToken, token) => {
      let token = null;

      const requestBody = {
        token: token
      };

      return fetch(url, {
          method: 'POST',
          body: JSON.stringify(requestBody)
        })
        .then((response) => response.json())
        .then((responseJSON) => {
          console.log(responseJSON); // <-- this shows the correct JSON data
          resolve(responseJSON);
        }).catch((error) => {
          reject(error);
        });
    });
  });
}

调用fetchFromAPI时,使用await,如

const apiData = await fetchFromAPI();

您也可以使用 .then 捕获响应并将其存储在 state 中,例如

fetchFromAPI.then((data) => {
   // use data here
});

希望这会有所帮助!