异步反应挂钩

时间:2020-06-08 06:35:00

标签: reactjs react-native react-hooks

我想在运行获取之前在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,但是我该如何解决这种情况?

如果有人可以帮助我:)

感谢社区,

4 个答案:

答案 0 :(得分:1)

为什么不以其他方式使用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); 

答案 1 :(得分:0)

也许在await之前添加AsyncStorage可以帮助您:

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;

答案 2 :(得分:0)

if (slots[greet] != null) 
        {

            var validateGreet = ValidateUserGreeting(slots[greet]);
            if (validateGreet.IsValid) 
            {
                return Close(sessionAttributes,
                              "Fulfilled",
                              new LexResponse.LexMessage
                              {
                                  ContentType = "PlainText",
                                  Content = String.Format("Hello Kindly choose one option")
                              },
                              new LexResponse.LexResponseCard
                              {
                                  Version = 1,
                                  ContentType = "application/vnd.amazonaws.card.generic",
                                  GenericAttachments =
                                  {
                                  new LexResponse.LexGenericAttachments
                                  {
                                      Buttons =
                                      {
                                         new LexResponse.LexButton
                                         {
                                             Text = "Shop Now",
                                             Value = "Shop Now"
                                         }
                                      },
                                      AttachmentLinkUrl = null,
                                      Title = "Shopping",
                                      SubTitle = "Sub Shopping",
                                      ImageUrl = null
                                  }
                                  }
                              }
                              );
            }

我认为一个承诺在解决时就需要,并且要抓住一个错误捕获的地方

答案 3 :(得分:0)

您不应该那样实现钩子,只要使用此钩子的组件重新呈现,它将导致多次调用获取。 尝试以下方法:

const useCallApi =  url => {
  const [data, setData] = useState(null)
  useEffect(() =>{
    const fetchData = async () =>{
      const [instance, token] = await Promise.all([
        AsyncStorage.getItem('instance'),
        AsyncStorage.getItem('token')
      ]);
      
      // I assume that your useFetch is a hook that retruen a Promise of data
      const fetchedData = await useFetch(`${instance}/api/v1/${url}`, {
        headers: {
          Authorization: `Bearer ${token}`
        }
      });

      setData(fetchedData)
    }
    fetchData()
  },[url])

  return data;
};