react-native - 无法在 React-Native 中获取 fetch(url)

标签 react-native

我正在尝试使用 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

设备:安卓

最佳答案

一些想法:

  • 如果是 iOS,则需要远程 url 为 https 或禁用此安全功能;
  • 您可能需要将 fetch() 标记为异步函数;
  • 尝试在没有 promise 的情况下进行异步获取。
  • 关于react-native - 无法在 React-Native 中获取 fetch(url),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48211465/

    相关文章:

    react-native - 如何使用 react 原生图像选择器添加多个图像

    javascript - 如何显示当前的获取 url 以及我的状态发生了什么?

    android - 一些自定义标记不会出现在 Android react-native-maps 上

    react-native - 如何查看当前设置的本地通知?

    javascript - 未知参数类型 '_Bool' EAzureBlobStorageFile 和异常 '*** -[__NSArrayM objectAtIndexedSubscript :]

    javascript - Spinner 在 onEndReachedThreshold Flatlist 中不起作用

    android - 如何解决 React Native Expo 项目中的 Uncaught Error :29. 0.0

    android - 构建版本 : Version code not found in manifest

    ios - 在启动画面加载 iOS 之前 react native 黑屏

    html - 带有 flexbox 的粘性页脚