【问题标题】:React Native Fetch won't executeReact Native Fetch 不会执行
【发布时间】:2017-07-27 07:44:09
【问题描述】:

我花了几个小时试图弄清楚如何使用 fetch 查询 API,但我什至无法执行 fetch 命令。

我对 Javascript 很陌生,所以希望有人能指出一些愚蠢的错误,因为我什至无法通过使用 fetch 的第一步。

这是我无法工作的非常小的 sn-p 代码。

var req = new Request('http://myapp.com:8000/api/posts', {method: 'GET'});
console.log("1");
fetch(req).then(function(res) {
    console.log("2");
    return res.json();
    })
console.log("3"); 

控制台每次都记录“1”和“3”,但从未记录“2”。

有人知道怎么回事吗?

另外,我正在向本地运行的 django 服务器发出 fetch 请求,并且通过监视服务器,当我运行我的 react-native 应用程序时,甚至没有向服务器发出任何请求。

【问题讨论】:

标签: javascript android api react-native fetch


【解决方案1】:

直接用fetch试试,在Networking页面看看是怎么做的:

var url = 'http://myapp.com:8000/api/posts';
console.log("1");
fetch(url).then(function(res) {
    console.log("2");
    return res.json();
    })
console.log("3"); 

【讨论】:

  • 我对 OP 也有同样的问题,在我的情况下这并没有解决问题
  • 请发表问题并添加相关代码,这样会更容易帮助您。
【解决方案2】:

这是另一种获取数据的方法

 fetch("http://date.jsontest.com/")
 console.log("1");
  .then((response) => response.json())

  .then((responseData) => {
    console.log("2");
    this.setState({date: responseData.date});
  })
  .done();
}

【讨论】:

    【解决方案3】:

    尝试添加一个 catch 来检查是否有任何错误。

    fetch(url).then(function(res) {
        console.log("2");
        return res.json();
    }).catch((error) => {
     console.error(error);
    });
    

    【讨论】:

    • 我对 OP 也有同样的问题,就我而言,这并没有解决问题。此外,console.error(error) 行也从未执行过。另一个面临这个问题的人在this post
    猜你喜欢
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多