Javascript 无法在控制台中记录api结果

Javascript 无法在控制台中记录api结果,javascript,reactjs,Javascript,Reactjs,这可能是最简单的事情,但我下面的控制台日志无法查看api结果,有人知道为什么吗,顺便说一句,我是新手 componentDidMount() { this.setState({ loading: true }) console.log('app mounted'); fetch('https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=8') .the

这可能是最简单的事情,但我下面的控制台日志无法查看api结果,有人知道为什么吗,顺便说一句,我是新手

componentDidMount() {
    this.setState({ loading: true })
    console.log('app mounted');
    fetch('https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=8')
        .then(data => data.json())
        .then(data => this.setState({ data: data.articles, loading: false}))
        console.log('Results -', JSON.stringify(this.data));
} 

您可以在setState函数的回调中记录结果,如下所示:

this.setState({ data: data.articles, loading: false}, () => console.log(data.articles))

所以,你首先要知道的是,你在履行承诺。承诺是异步的,这意味着如果您要编写这些代码行

let a = "a"

fetch('https://newsapi.org/...')
  .then(() => { a = "b"; }

console.log(a) // "a"
结果将是一个错误,因为JavaScript将启动本例中创建承诺的任何内容,然后继续执行本例中console.loga后面的行。在您的情况下,.then部分将在promise完成它所做的任何事情后执行,等待网络流量恢复

所以你的情况是

// You set the state
this.setState({ loading: true })

// You log
console.log('app mounted');

// You create a promise
fetch('https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=8')
    // all of these then things will be called when the network traffic finishes
    .then(data => data.json())
    .then(data => this.setState({ data: data.articles, loading: false}))

    // this line is not part of the then so this is what actually gets called next
    // so here you are still logging the original state of this.data not the one after the network traffic
    console.log('Results -', JSON.stringify(this.data));


    // some time in the future your thens will be executed
这里的第二件事是您正在记录这个.data。您实际上想要记录这个.state.data。所以你的代码应该是这样的

componentDidMount() {
    this.setState({ loading: true })
    console.log('app mounted');
    fetch('https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=8')
        .then(data => data.json())
        .then(data => this.setState({ data: data.articles, loading: false}))
        .then(() => {
            console.log('Results', this.state.data);
        })

} 
您的console.log'Results-',JSON.stringifythis.data;甚至在返回数据之前执行

因此,要记录结果,请执行以下操作:

将console.log作为setState的回调,因为它是一个异步函数:

fetch('https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=8')
        .then(data => data.json())
        .then(data => this.setState({ data: data.articles, loading: false}, () => {'Results -', JSON.stringify(data)}));

也许添加调用函数的位置?看起来您正在fetch返回之外进行日志记录。数据尚不可用。将log语句移到final then子句中。感谢您的输入,我已接受答案并对您的两个输入进行了投票。您确定我的答案不正确吗?你看到一个未定义的日志了吗?是的。如果您尝试在回调之外记录this.state.data,它通常会出现前面的结果,因为this.setState本质上是异步的。像这样记录最后一个也是竞争条件,因为setState不返回承诺。好,但更大的问题更多的是关于在获取重新调整之前记录日志的疯狂竞争条件。如果在获取之前需要同时进行日志记录的任何内容都不是竞争条件,那么它根本就不起作用。