简体   繁体   English

React Native 将异步 function 导出为组件

[英]React Native exporting asynchronous function into a component

I am trying to export this function axiosWithToken into my component so that when I call 'axiosWithToken' it will return the axios.create object so i can build the rest of my axios request off of it. I am trying to export this function axiosWithToken into my component so that when I call 'axiosWithToken' it will return the axios.create object so i can build the rest of my axios request off of it. However, it does not work as expected but doesn't give any errors.但是,它没有按预期工作,但没有给出任何错误。 If I gut out this file and put it inside the component it works.如果我删除这个文件并将其放入组件中,它就可以工作。 Below is my component file I minimized it for readability.下面是我的组件文件,为了便于阅读,我将其最小化。 This has also happened to me with other asynchronous functions so I'm curious what I am doing wrong.其他异步函数也发生在我身上,所以我很好奇我做错了什么。

import axiosWithToken from './axiosWithToken'
const response = axiosWithToken.get(....)

This is the axiosWithToken file这是 axiosWithToken 文件

import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useState } from 'react';

const axiosWithToken = async () => {
  const [token, setToken] = useState('');
  try {
    const value = await AsyncStorage.getItem('@token');
    setToken(value);
    console.log(token);
  } catch (e) {
    // error reading value
    console.log('error getting value');
  }

  return axios.create({
    baseURL: 'http://10.0.2.2:3000',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
    },
  });
};

export default axiosWithToken;

You're trying to get a value from an async function without await?您正在尝试从异步 function 中获取值而不等待?

const response = axiosWithToken.get(....)
                ^
              await

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM