开发者问题收集

异步反应钩子

2020-06-08
411

我想在 React-Native 中创建异步 React 钩子,以便在运行获取之前获取 AsyncStorage 数据。

示例:

const useCallApi = async url => {
  const [instance, token] = await Promise.all([
    AsyncStorage.getItem('instance'),
    AsyncStorage.getItem('token')
  ]);

  const data = useFetch(`${instance}/api/v1/${url}`, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });

  return data;
};

export default useCallApi;

但是这个钩子返回错误 Unhandled promise rejection 。我认为问题出在 useFetch 钩子之前的 await ,但我该如何解决这个问题?

如果有人能帮助我 :)

谢谢社区,

3个回答

为什么不换一种方式使用 AsyncStorage?只需初始化完成后,你就可以从任何地方同步访问 AsyncStorage。通过 react-native-easy-app ,你可以像这样操作 AsyncStorage

import { XStorage } from 'react-native-easy-app';
import { AsyncStorage } from 'react-native';

 export const RNStorage = {
     token: undefined, 
     isShow: undefined, 
     userInfo: undefined
 };

const initCallback = () => {

     // From now on, you can write or read the variables in RNStorage synchronously

     // equal to [console.log(await AsyncStorage.getItem('isShow'))]
     console.log(RNStorage.isShow); 

     // equal to [ await AsyncStorage.setItem('token',TOKEN1343DN23IDD3PJ2DBF3==') ]
     RNStorage.token = 'TOKEN1343DN23IDD3PJ2DBF3=='; 

     // equal to [ await AsyncStorage.setItem('userInfo',JSON.stringify({ name:'rufeng', age:30})) ]
     RNStorage.userInfo = {name: 'rufeng', age: 30}; 
};

XStorage.initStorage(RNStorage, AsyncStorage, initCallback); 
rufeng
2020-06-10

也许在 AsyncStorage 之前添加 await 会对您有所帮助:

const useCallApi = async url => {
  const [instance, token] = await Promise.all([
    await AsyncStorage.getItem('instance'),
    await AsyncStorage.getItem('token')
  ]);

  const data = useFetch(`${instance}/api/v1/${url}`, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });

  return data;
};

export default useCallApi;
Sina Salami
2020-06-08
const useCallApi = async url => {
let instance = null;
let token = null;
  Promise.all([
    AsyncStorage.getItem('instance'),
    AsyncStorage.getItem('token')
  ]).then(d=>{
instance = d[0];
token = d[1];
}).catch(e=>throw e);
  const data = useFetch(`${instance}/api/v1/${url}`, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
  return data;
};

export default useCallApi;

我认为 Promise 在解析时需要 then 以及用于捕获错误的 catch

vinayak shahdeo
2020-06-08