typescript - 如何在本机反应中从假服务器获取数据?
问题描述
我在笔记本电脑中制作了一个假服务器来获取数据。这是其中的数据:
[
{
"id": 1,
"firstName": "Bill",
"lastName": "Gates",
"email": "bill@microsoft.com",
"phone": "1234567898",
"role": "Accountant",
"org": "Organization 1"
},
{
"id": 2,
"firstName": "Mark",
"lastName": "Zuckerberg",
"email": "mark@facebook.com",
"phone": "9876543212",
"role": "Admin",
"org": "Organization 1"
}
]
我使用 npm run mock:api 运行服务器
我想从中获取数据并显示在我的物理 android 设备(手机)中。这是我尝试过的代码:
constructor(props) {
super(props);
this.state = {
users_fake: []
}
}
componentDidMount() {
fetch("https://192.168.43.164:4000/users")
.then(response => response.json())
.then((responseJson)=> {
console.log('Response = ' + responseJson);
this.setState({
loading: false,
users_fake: responseJson
})
})
.catch(error=>console.log(error))
和这个:
fetch("http://localhost:4000/users")
.then(response => response.json())
.then((responseJson)=> {
this.setState({
loading: false,
users_fake: responseJson
})
})
.catch(error=>console.log(error))
和这个:
fetch('http://localhost:4000/users', {
method: 'GET'
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
users_fake: responseJson
})
})
.catch((error) => {
console.error(error);
});
}
我显示这样的数据:
{ this.state.users_fake.map((user, index) => {
return (
<Text>{user.firstName} {user.lastName}</Text>
)
})}
但我在控制台中收到错误:
WARN Possible Unhandled Promise Rejection (id: 16):
TypeError: Network request failed
我应该怎么做才能获取数据并显示它?
解决方案
在 catch 函数中添加抛出错误
fetch("https://192.168.43.164:4000/users")
.then(response => response.json())
.then((responseJson)=> {
console.log('Response = ' + responseJson);
this.setState({
loading: false,
users_fake: responseJson
})
})
.catch(error=>{console.log(error);
throw error;})
希望这可以帮助!
推荐阅读
- sparql - 空的 TDB2 查询结果
- java - 错误:“java”插件已应用,但与 Android 插件不兼容
- jquery - 刷新 div 并重新加载脚本
- ibm-mq - 尝试在 DLQ 中浏览消息时获取 mqrc 2080
- android - 是否有“片段完成附加”事件?
- parallel-processing - pandoc 有时无法找到 utf8.md 文件
- types - 为什么这个简单的索引变量 gettng 在 Julia 中是 Box-ed?
- java - 启动线程并进行后台活动
- c# - 有没有办法使用 C# 硬删除(移位删除)目录及其文件?
- visual-studio - mfc OnVScroll 没有在 MDI 主框架类中被调用