从 REST API 获取数据时,Render 被调用两次 [英] Render is called twice when fetching data from a REST API
问题描述
我正在尝试使用 React 与 REST API 交互,并且我意识到当我获取数据时,render
被调用一次没有数据,然后再次使用数据.
I am trying to interact with a REST API using React, and I have realized that when I fetch the data, render
is called once without the data, and then again with the data.
当我尝试处理此数据时,这会引发异常,但我可以使用 if 语句来检查数据是否为空.但是,我不确定是否需要这样做.
This throws an exception when I try to process this data, but I can use an if statement to check if data is null or not. However, I am not sure if that's needed.
class App extends Component {
state = {
TodoList: {},
};
componentWillMount() {
axios.get("http://localhost:5001/1").then((response) => {
this.setState({
TodoList: response.data,
});
});
}
render() {
console.log(this.state);
return <h1>hello </h1>;
}
}
这是我在控制台中看到的:
This is what I see in in the console:
推荐答案
这很正常.
你的App
组件流程如下:
- 执行
render
方法加载组件 - 在
componentDidMount
中执行代码 - 调用
axios.get
这是异步操作 - 从第 2 步接收数据,使用
this.setState
更新组件状态 App
组件检测到状态更新,因此执行render
方法再次加载组件
- Execute
render
method to load the component - execute codes in
componentDidMount
- Calling
axios.get
which is async operation - Receive data from step 2, update component state by using
this.setState
App
component detected there's an update on state, hence executerender
method to load component again
因此,你绝对应该处理 this.state.TodoList
没有数据的情况,这种情况发生在第一次加载
Hence, you should definitely handle the case where this.state.TodoList
has no data, which happened at first load
更新:
组件生命周期 componentWillMount
现在已弃用,这意味着您不应再使用它.用 componentDidMount
代替它.从功能上讲,它们在您的示例中应该没有区别
component lifecycle componentWillMount
is now deprecated which means you shouldn't be using it anymore. Replace it with componentDidMount
instead. Functionally wise they should be no difference in your example
这篇关于从 REST API 获取数据时,Render 被调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!