问题描述
import React,{ useEffect,useState } from "react";
import { StyleSheet,View,Button,ScrollView } from "react-native";
import { Spinner,List,ListItem,Text } from "native-base";
import axios from "axios";
const Todo = ({ navigation }) => {
const [tasks,setTasks] = useState();
const [isLoading,setIsLoading] = useState(false);
const loadTasks = async () => {
try {
const tasks = await axios.get("http://localhost/tasks");
setIsLoading(true);
} catch (e) {
alert(e);
}
};
useEffect(() => {
loadTasks();
},[]);
if (isLoading) {
return (
<View >
<View>
<ScrollView>
<List>
<ListItem>
<Text>Simon Mignolet</Text>
</ListItem>
</List>
</ScrollView>
</View>
<View style={styles.btn}>
<Button
bordered
primary
title="Goto homescreen"
onPress={() => navigation.navigate("Home")}
/>
<Button title="Add task" />
</View>
</View>
);
} else {
return <Spinner />;
}
};
在上面的代码中,我使用 json 服务器使用 axios 获取数据。但是在获取数据时,它显示网络错误。并且没有数据显示。我正在使用 axios 对 JSON 服务器进行 api 调用。并在 EXPO Go 应用程序中对其进行测试,该应用程序可在 Playstore 中获得。但是从 catch 块中,它抛出异常为“网络错误。请任何人帮助我。”
解决方法
您忘记了 port
,
改变
const tasks = await axios.get("http://localhost/tasks");
到
const tasks = await axios.get("http://localhost:3000/tasks");
// 3000 or whatever port you are using for backend
要在您的移动设备上成功运行它,您必须将 localhost
替换为 IPv4 of your local network