React.js组件生命周期,状态行为和JavaScript的异步性质 [英] React.js component life cycle, state behavior and asynchronous nature of JavaScript

查看:73
本文介绍了React.js组件生命周期,状态行为和JavaScript的异步性质的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对预期结果和实际结果有疑问。即使从 componentWillMount()调用 fetchData() fetchnumberOfCommits()方法数组仍然没有数据。但最后,render方法被调用两次,其中数组已从API获取数据。
我在上面提到的调用render方法的方法中都调用了 setState()方法。
我的问题是为什么一旦调用这两个方法,数组就不能获取数据?什么时候数组获取数据?

I have an issue with the expected result and the actual result. Even though the fetchData() and fetchnumberOfCommits() methods are called from the componentWillMount() still the array has no data . But at the end, the render method is called twice, where the array has got data from the API. I called the setState() method in both the above-mentioned methods where it calls the render method. My problem is why does the array does not get data as soon as the two methods are called? and at what point array gets data ?

代码示例

推荐答案

我从 componentWillMount()改为 componentDidMount(),但我遇到了同样的问题。原因是JavaScript的异步性质。当你使用promises时,它不会等到你从API调用得到结果。它只是按顺序运行代码,保持承诺单元获取数据。这就是我得到一个空数组的原因,即使该函数被调用。

I changed from componentWillMount() to componentDidMount() as well, but I got the same problem . Reason for that was the asynchronous nature of JavaScript . When you use the promises it doesn't wait until you get the results from the API call. It just run the codes down the order keeping a promise unitl it get data. That is the reason that I got an empty array even though the function was called.

你可以使用 async / await 使代码同步,然后它将等待,直到您从API调用获得结果。
如果运行以下代码示例,您可以在控制台中看到结果,其中 fetchData1()给出一个空数组, fetchData2( )为数组提供数据。另外,如果你仔细检查控制台,你会看到当调用 setState()函数时 render()方法触发器。

You can use async/await to make the code synchronized and then it will wait until you get the results from the API call. If you run the following code example you can see the results in the console where fetchData1() gives an empty array and the fetchData2() to gives the array with data .Further if you examine the console well, you will see that when the setState() function is called the render() method triggers.

import React, { Component } from 'react';

class App extends Component {
  constructor(){
    console.log('This is from constructor');
    super();     
    this.state={
      repositories:[],
  }  
  }
  componentDidMount(){
    console.log('This is from componentDidMount');
    this.fetchData1();
    this.fetchData2();
  }
  fetchData1(){
        console.log('This is function is using promises');
        fetch('https://api.github.com/users/94ju/repos').then(results => results.json()).then(repositories =>this.setState({ 
          repositories
        })).then( 
          console.log( this.state.repositories),
          console.log(this.state)
        ) 
        console.log('End of using promises')

  }
  async fetchData2(){
    console.log('This is function is using async-await');
    const check =await fetch('https://api.github.com/users/94ju/repos');
    const checkjson =await check.json();
    console.log('Before setState');
    this.setState({ async_repositories: checkjson });
    console.log( this.state.async_repositories);
    console.log(this.state);
    console.log('End of async-await');
}
  render() {
    console.log("Starting render function");
    const repo =this.state;
    console.log(repo);
    console.log('Ending render function');
    return (
      <div>

      </div>
    );

  }
}

export default App;

这篇关于React.js组件生命周期,状态行为和JavaScript的异步性质的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆