我对预期结果和实际结果有疑问。即使从仍然调用fetchData()和fetchnumberOfCommits()方法componentWillMount(),数组也没有数据。但是最后,render方法被调用了两次,数组从API那里获取了数据。我setState()在上述两个方法中都调用了该方法,其中它调用了render方法。我的问题是,为什么在调用这两个方法后数组不立即获取数据?在什么时候数组获取数据?
fetchData()
fetchnumberOfCommits()
componentWillMount()
setState()
代码示例
我也从componentWillMount()更改 componentDidMount()为,但遇到了同样的问题。原因是JavaScript的异步特性。当您使用诺言时,它不会等到您从API调用中获得结果。它只是将代码按顺序运行,以保证诺言获得数据。这就是即使调用该函数也得到一个空数组的原因。
componentDidMount()
您可以使用async/await 来使代码同步,然后它将等待直到您从API调用中获得结果。如果运行以下代码示例,则可以在控制台中看到结果,其中fetchData1()给出了一个空数组,fetchData2()to给出了包含数据的数组。此外,如果您对控制台进行了仔细的检查,您将看到setState()调用该函数的render()方法触发了。
async/await
fetchData1()
fetchData2()
render()
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;