我正在尝试使用 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 .
代码修复:
我只是用我的 ipv4 地址替换了 localhost 为 http://myserveripv4address:3000/listData它奏效了。
版本:
react-native@0.50.4
设备:安卓
最佳答案
一些想法:
关于react-native - 无法在 React-Native 中获取 fetch(url),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48211465/