不知道为什么 React 中的这个异步调用有效



我正在玩reactjs,这是我正在做的事情: 正在从 API 检索数据并显示数据 使用公理调用 API。 我知道 axios 调用是异步的,并且是基于承诺的。

我的理解是,在反应中,只有在组件挂载后才能调用"setState" (这发生在组件DidMount中(。 因此,对API的调用是在"componentDidMount"中进行的。

我不清楚的是:为什么这有效,为什么我会显示数据?

我在这里读到"渲染"在"组件DidMount"完成之前被触发

因此,鉴于"渲染"在"组件DidMount"之前,我很困惑为什么数据加载并显示正常?

我还查看了这个站点,它使用一些标志来确定数据是否已加载,然后决定是否显示微调器 我也不必做任何这样的事情 所以虽然它确实显示数据,但我相信还有更多......

这是代码:

class StudentsPage extends React.Component{
constructor(props){
super(props);
this.state = {
isLoaded: false,
studentListArray: []
}
}

componentDidMount(){
/** now get results from api call and need to set the result to the state of this class */
/** setting state MUST happen using setState and no other way - this is important */
/** NOTE below call to setState will ONLY modify the attribute 'studentListArray' of state
*  if there were other attributes / properties in state they would not get impacted / modified
*  so setState is more like setters for individual properties 
*  you can change multiple properties in one setter OR call setState for each property you want to change !
*/
/** define the endpoint to be called */
const baseUrl = process.env.REACT_APP_API_URL + "/studentList/";
axios.get(baseUrl).then(({data}) => {
this.setState(
{ studentListArray: data }
);            
})
}
render(){ 
return(
<React.Fragment>
<table className="table">
<thead>
<tr>
<th>Sudent ID</th>
<th>Student subject</th>
</tr>
</thead>
<tbody>
{this.state.studentListArray.map((student) => {
return (<tr>
<td>{student.id}</td>
<td>{student.subject}</td>
</tr>);
})}
</tbody>
</table>
</React.Fragment>
);
}
}

挂载基于类的组件时,其生命周期方法按以下顺序执行:

  1. constructor()
  2. static getDerivedStateFromProps()
  3. render()
  4. componentDidMount()

在您的情况下,挂载StudentPage组件后,它会立即尝试获取数据,然后触发组件更新/重新渲染。

当组件重新呈现时,它会按以下顺序调用以下生命周期方法:

  1. static getDerivedStateFromProps
  2. shouldComponentUpdate()
  3. render()
  4. getSnapShotBeforeUpdate()
  5. componentDidUpdate()

如果您在render()componentDidMount()componentDidUpdate()中放置断点或简单console.log(),您将能够更清楚地可视化这一点。

这纯粹是我这边的猜测,但有可能您调用的(我假设本地(服务器正在更快地响应您期望的数据,因此数据似乎在首次挂载时很容易获得。

如果你想了解更多关于 React 的生命周期方法,那么不要犹豫,参考官方的 React 文档。

最新更新