【问题标题】:How to print JSON data to the console only after fetch in React Native?仅在 React Native 中获取后如何将 JSON 数据打印到控制台?
【发布时间】:2018-07-02 17:09:39
【问题描述】:

我已经尝试了以下代码:

const response =await fetch('https://facebook.github.io/react-native/movies.json');
const json= await response.json();
console.log(json.result);

将获取的 JSON 数据打印到控制台,但它不起作用。如何将获取的数据直接写入控制台?

【问题讨论】:

  • await 与承诺一起使用。完成承诺后,您可以登录。
  • 您的代码有问题。我在下面演示了一个解决方案。但是询问使用数据创建视图应该是一个单独的问题,因为它与您的代码示例无关。

标签: json react-native fetch-api


【解决方案1】:

使用同步/等待的答案(您在问题中使用)

const fetchAndLog = async () => {
    const response = await fetch('https://facebook.github.io/react-native/movies.json');
    const json = await response.json();
    // just log ‘json’
    console.log(json);
}

fetchAndLog();

【讨论】:

  • 如果响应不是有效的 JSON(例如服务器故障),我根本不会打印
【解决方案2】:
fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
    console.log(responseJson);
})

【讨论】:

    【解决方案3】:

    我正在使用这种方式,它工作正常。

    fetch('https://facebook.github.io/react-native/movies.json')  
     .then((response) => response.text())
     .then((responseText) => {
         console.log(JSON.parse(responseText));
     })
     .catch((error) => {
         console.log("reset client error-------",error);
    });
    

    下面用于特定的方法请求。 Headers 和 Body 用于向服务器发送数据。通过这种方式,我们可以请求获取函数的类型和方法。

          fetch(url, {
                method: 'POST', 
                timeout:10000,
                headers: headers,
                body: JSON.stringify(params) 
            })  
            .then((response) => response.text())
            .then((responseText) => {
                 console.log(JSON.parse(responseText));
            })
            .catch((error) => {
                 console.log("reset client error-------",error);
            });
        });
    

    【讨论】:

    • 它工作正常。感谢您提供有关获取操作中使用的 requestType 或 Method 的详细信息。
    【解决方案4】:

    在我看来,这是正确的写作方式:

    async function fetchblogEntry(){
        const response=await fetch('https://facebook.github.io/react-native/movies.json');
        console.log(response.json())
    }
    
    fetchblogEntry()
    

    【讨论】:

      猜你喜欢
      • 2021-02-02
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多