从 REST API 获取数据时,Render 被调用两次 [英] Render is called twice when fetching data from a REST API

查看:27
本文介绍了从 REST API 获取数据时,Render 被调用两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 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组件流程如下:

  1. 执行render方法加载组件
  2. componentDidMount
  3. 中执行代码
  4. 调用 axios.get 这是异步操作
  5. 从第 2 步接收数据,使用 this.setState
  6. 更新组件状态
  7. App 组件检测到状态更新,因此执行 render 方法再次加载组件
  1. Execute render method to load the component
  2. execute codes in componentDidMount
  3. Calling axios.get which is async operation
  4. Receive data from step 2, update component state by using this.setState
  5. App component detected there's an update on state, hence execute render 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屋!

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