Axios.get()不是React Native Axios的函数

yrdbyhpb  于 2023-04-20  发布在  iOS
关注(0)|答案(1)|浏览(144)

我写了一个简单的项目使用React原生.我需要使用axios解析一个网站,但我得到这个错误在应用程序的Web版本:“类型错误:axios.get不是一个函数”,在android应用程序中,我得到了这个:“可能的未处理的Promise拒绝(id:0):TypeError:undefined不是函数TypeError:undefined不是一个函数。

const axios = require("axios")
class Parser {
    async getMediaList(page) {
        const url = baseUrl + page
        const response = await axios.get(url)
        //cheerio code
 
        return mediaList
    }
}

module.exports = new Parser()

我这样使用这个函数:

useEffect(() => {
  const getData = async () => {
    const data = await Parser.getMediaList();
    setMediaData(data);
  };
  getData()
}, []);

在简单的npm项目中,没有React Native,一切都很完美
工作项目的依赖关系:

"dependencies": {
    "axios": "^1.3.4",
    "cheerio": "^1.0.0-rc.12"
  }

非工作项目的依赖项:

"dependencies": {
    "@expo/webpack-config": "^18.0.1",
    "@react-navigation/bottom-tabs": "^6.5.7",
    "@react-navigation/native": "^6.1.6",
    "@react-navigation/native-stack": "^6.9.12",
    "@react-navigation/stack": "^6.3.16",
    "axios": "^1.3.5",
    "cheerio": "^1.0.0-rc.12",
    "expo": "~48.0.10",
    "expo-font": "~11.1.1",
    "expo-status-bar": "~1.4.4",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-native": "0.71.6",
    "react-native-navigation-bar-color": "^2.0.2",
    "react-native-safe-area-context": "4.5.0",
    "react-native-screens": "~3.20.0",
    "react-native-web": "~0.18.10"
  },

我该怎么解决?

chhqkbe1

chhqkbe11#

在文件中创建:

import axios from "axios";
    
    export function getMediaList(){
       const url = baseUrl + page
       return axios.get(url);
    }

在组件中使用它

import { getMediaList } from "url file path";

useEffect(async () => {
   try{
      const data = await getMediaList();
      setMediaData(data);
   } catch(err){
      console.log(err);
   }

}, []);

相关问题