【发布时间】:2018-01-11 16:13:26
【问题描述】:
我正在尝试使用 react-native 中的 fetch(方法:GET)从 api url 检索 json 响应。
constructor(props){
super(props);
this.state = {jsonData: {}};
}
componentWillMount() {
console.log("inside componentWillMount");
fetch('http://localhost:3000/listData')
.then((response) => {console.log('response: '); return response.json();})
.then((responseJson) => {console.log('responseData: '+JSON.stringify(responseJson)); return this.setState({jsonData: responseJson});})
.catch((err) => {console.log(err)});
}
api以这种格式返回数据:
{
object: 'list',
data: [...]
}
api url 通过 curl 工作。我还尝试通过安装 node-fetch 来使用 node 独立运行代码的 fetch 部分,并正确打印了 responseData。 但是,在 react-native 中,它不会在 fetch 的 then 函数中打印任何控制台日志语句,也不会设置 jsonData 的状态。
你能告诉我可能是什么问题吗?我已经在谷歌上搜索了很长时间,试图找出可能是什么问题。
编辑 我尝试了异步获取如下:
componentWillMount() {
console.log("inside componentWillMount");
this.fetchData().done();
}
async fetchData(){
const response = await fetch('http://localhost:3000/listData')
const json = await response.json();
const data = json.url;
console.log('data'+url);
}
不过,同样的问题仍然存在。 我无法理解为什么它适用于 facebook url 而不是我的本地 api url
解决方案
感谢 Michael Cheng 为我指明了正确的方向。
我找到了这个链接:
https://github.com/react-community/create-react-native-app/issues/154 。
代码修复: 我刚刚将 localhost 替换为我的 ipv4 地址 http://myserveripv4address:3000/listData 并且它起作用了。
版本:
react-native@0.50.4
设备: Android
【问题讨论】:
-
1.由于看起来您正在本地运行的服务器上进行测试,服务器日志是否显示已收到获取请求? 2. 这看起来是一个错误:
return this.setState({jsonData: responseJson});我不知道你为什么要返回setState电话。改写为this.setState({jsonData: responseJson}); return; -
您对获取请求 Michael 的看法是正确的。本地服务器日志中没有获取请求的任何内容。
-
我已经更新了你提到的 setState。同样的问题仍然存在。我还在设备日志中注意到我的本地 api url 出现此错误:'网络请求失败 - node_modules\react-native\node_modules\whatwg-fetch\fetch.js:441:29 in onerror'。我用谷歌搜索了这个错误,似乎在超时时会抛出这个错误。我将本地 api url 替换为 'facebook.github.io/react-native/movies.json' 只是为了测试目的并且获取工作。因此,问题是在 fetch 中调用本地 api url 时。我正在android中进行测试。我也尝试过异步。还是一样的问题
-
curl 和使用本地 api url 的独立获取代码有效,但在 react-native 中无效
-
非常感谢 Michael Cheng 为我指明了正确的方向。我找到了这个链接:github.com/react-community/create-react-native-app/issues/154。我刚刚用我的 ipv4 地址替换了 localhost,它工作了。
标签: react-native