我对预期结果和实际结果有疑问。即使从 componentWillMount()
调用 fetchData()
和 fetchnumberOfCommits()
方法,数组仍然没有数据。但最后,render 方法被调用两次,其中数组从 API 获取了数据。
我在上述两个方法中调用了 setState()
方法,其中它调用了 render 方法。
我的问题是为什么调用这两个方法后数组没有立即获取数据?数组在什么时候获取数据?
最佳答案
渲染方法会在组件首次安装时调用,并在收到数据且状态发生更改时再次调用。这就是为什么您会看到渲染方法被调用两次。
componentWillMount()
在 React 16.3 中已弃用。您应该使用 componentDidMount()
来获取数据,并且您应该期望组件在获取数据之前至少渲染一次,因此您需要渲染 null
或获取数据之前的加载状态。我提供了一个示例,说明如何检查它是否已正确加载并显示加载消息。
class App extends React.Component {
constructor() {
super();
this.state = {
check: true,
repositories: [],
commits: [],
};
}
componentDidMount() {
this.fetchData();
this.fetchNumberOfCommits();
}
fetchData() { /*...*/ }
fetchNumberOfCommits() { /*...*/ }
isLoaded() {
return this.state.respositories.length > 0;
}
render() {
const { repositories } = this.state;
if(isLoaded) {
return repositories.map(repo => {
return (
<Api
repo={repo.name}
createdDay={repo.createdDay}
/>
);
});
}
return <h1>Loading repos...</h1>;
}
}
关于javascript - React.js 组件生命周期、状态行为和 JavaScript 的异步特性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52922038/