React Native AsyncStorage:获取令牌并在重构 API 提取中使用它

React Native AsyncStorage: Get Token and Use it in a refactored API fetch

我决定将所有 API 调用放在一个单独的文件中,它们都是无状态的。

const get = endPoint => {
  let token = "c8c17003468314909737ae7eccd83d4b6eecb792"; //I have put this token here manually    
  return fetch(endPoint, {
    method: "GET",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Authorization: "Token " + token
    }
  }).then(response => response.json());
};

并且在同一个文件中我有实际的 API 调用。例子如下

export const loadGroups = () => {
  const endPoint = "https://xxxx.com/api/groups/";
  return get(endPoint);
};

当我按如下方式从各种组件调用 API 时,这非常有效。

import { loadGroups } from "../../api";
componentDidMount() {
    loadGroups()
      .then(responseJson => {
        this.setState({
          groups: responseJson
        });
      })
      .catch(error => {
        console.error(error);
      });
      }

但是,我想使用 AsyncStorage 来检索存储的令牌,它的应有性质是 return 一个承诺。当我在调用的每个组件中编写获取令牌并将其存储在 SetState 中的函数时,这很有效。我真的很想重构代码,使用 redux 对我来说很痛苦。

到目前为止,我已经编写了一个文件来获取令牌并且它return是一个承诺。

import { AsyncStorage, Text } from "react-native";

const MyToken = async () => {
  try {
    const retrievedItem = await AsyncStorage.getItem("userToken");
    const item = JSON.parse(retrievedItem);
    return item;
  } catch (error) {
    return null;
  }

};

export default MyToken;

并且在API文件中,我将上面的代码重写为

const get = endPoint => {
  MyToken().then(token => {
    console.log(token, "try 1"); //this works
    const lookupOptions = {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        Authorization: "Token " + token
      }
    };
    return fetch(endPoint, lookupOptions).then(response => {
      console.log(response.json(), "promise response,json");
      response.json();
    });
  });

};

但是,每当我在任何组件中调用 loadGroups().then()(如第一个示例)函数时,我都会收到 loadGroups.then() 无法解析的错误

有没有办法在没有状态、redux、mobx 的情况下解决这个问题,请记住我希望我的 API 代码在单独模块中的无状态函数中。

get 函数的 V2 中,您没有 returning 任何 Promise。要么在 get 函数中放置一个 return 语句,例如

const get = endPoint => {
  return MyToken().then(
    ...
  );
}

或 return Promise 显式地从该函数中,考虑以下代码片段

const get = endPoint => {
  return new Promise((resolve, reject) => {
    MyToken().then(token => {
      ...
      fetch(endPoint, lookupOptions)
      .then(response => response.json())
      .then(resolvedResponse => {
        resolve(resolvedResponse);
      }).catch(error => {
        reject(error);
      });
    });
  });
};

希望对您有所帮助!