【发布时间】:2020-06-03 16:19:36
【问题描述】:
我正在尝试从 API 获取数据(我使用 JSON 服务器创建了自己的 Rest API)。但我什么都拿不到。但是,当我导航到 localhost:3000/events 时,我能够看到数据。我的应用程序中没有其他错误。我只有在运行应用程序时才得到这个,它说网络请求失败。所有组件都工作正常。只是没有得到数据。我尝试了其他一些在线 API 仍然没有得到任何响应。我试过异步/等待。我正在使用带有 IOS 的应用程序,但也尝试过使用 Andriod。出现同样的问题。附上代码sn-ps。任何帮助将不胜感激。谢谢
创建了 getEvent 函数:
const { manifest } = Constants;
const api = manifest.packagerOpts.dev
? manifest.debuggerHost.split(`:`).shift().concat(`:3000`)
: `api.example.com`;
const url = `http://${api}/events`;
export function getEvents() {
return fetch(url)
.then(response => response.json())
.then(events => events.map(e => ({ ...e, date: new Date(e.date) })))
}
在 componentDidMount 中使用它
componentDidMount() {
// getEvents().then(events => this.setState({ events }));
setInterval(() => {
this.setState({
events: this.state.events.map(evt => ({
...evt,
timer: Date.now()
}))
});
}, 1000);
this.props.navigation.addListener("didFocus", () => {
getEvents().then(events => this.setState({ events }));
});
}
我正在尝试获取的数据。
{
"events": [
{
"title": "Demo a new app",
"date": "2020-03-29T13:45:18.000Z",
"id": "001c9b6d-00a9-465c-a2d3-afb7176a0a87"
}
]
}
【问题讨论】:
-
当您的服务器不工作或互联网连接不可用时,您将收到“网络请求失败”。所以请检查并使用相同的代码重试。在调试器中打印日志并检查。
-
我在连接到我自己的 REST API 时遇到了很大的问题,因为我的 url 也是错误的,请检查一下。
-
你能用 API 展示你的代码吗? , 那有什么帮助呢
-
@AnujSharma 嗨 Anuj,我是 React Native 的新手,对 expo snap 不熟悉,你只是想让我在 expo snap 上上传项目并与你分享链接吗?你将如何使用我在本地运行的 Rest API?谢谢
-
是的,但是如果您在本地使用 API,那么我将无法检查您的 API,但是当我刚开始做出反应时,我使用 alerts 来检查数据流。您也可以通过在各个阶段设置警报来做到这一点,例如首先打印您传递给 API 的数据,使用 alert(JSON.stringify(data)); 然后检查您传递的天气是否正确数据到 API 与否。这对您有很大帮助,如果对您没有帮助,请告诉我。
标签: react-native react-native-android react-native-ios