如何仅在 React Native 中获取后才将 JSON 数据打印到控制台?

How to print JSON data to the console only after fetch in React Native?

我试过以下代码:

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

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

fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
    console.log(responseJson);
})

使用 sync/await 的答案(您在问题中使用的)

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();

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

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 函数的类型和方法。

      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);
        });
    });

在我看来,这是正确的写法:

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

fetchblogEntry()