【问题标题】:Why ajax request should be done in componentDidMount in React components?为什么 ajax 请求应该在 React 组件中的 componentDidMount 中完成?
【发布时间】:2025-11-24 09:05:02
【问题描述】:

React 文档指出 ajax 请求应该从 componentDidMount 生命周期事件发起(参见 react docs)。

为什么要举办这个活动?

在大多数情况下,使用 ajax 加载数据时,我想显示某种加载栏,例如:

componentDidMount() {
   this.setState({isLoading: true});
   fetch(...)
      .then(...)
      .then(() => this.setState({isLoading: false})  
}

但这会触发render 方法3 次(初始渲染立即设置isLoading = true,然后设置isLoading = false

componentWillMount事件发送ajax请求有什么问题?

【问题讨论】:

标签: reactjs


【解决方案1】:

嗯,isLoading: true 可以是初始状态的一部分,在组件挂载后不需要设置它 => 只有 2 个渲染,而不是 3 个。

根据https://github.com/reactjs/react-redux/issues/210,从componentWillMount只调用一次render的后果是,如果setStaterender之后被异步调用,它不会有任何效果(如果我理解cmets正确)。

不确定setState 的回调是否有可能在render 之前执行,因此看不到加载屏幕,只有结果,因此有时它会“工作”(很可能在 DEV 中)但是实际上,这将是一个很难调试的竞争条件......

另见:https://reactjs.org/docs/faq-ajax.html

【讨论】:

  • 该问题已修复,因此从componentWillMount调用的setState将在渲染之前生效。在反应文档中仍然没有解释为什么应该在 componentDidMount 中完成 ajax 调用
  • 好吧,您不是直接从 componentWillMount 或 componentDidMount 调用 setState,而是从新的异步堆栈调用。我不知道如何通过各种方法的实时事件监听器来实现对 this 的引用。如果使用未记录的功能对您来说还不够吓人,并且想要一点兴奋它可能会起作用,甚至可能在未来的版本中,那么请放心,我不知道它是否会损坏
【解决方案2】:

重点是让你的 react 组件以初始状态渲染,这样你就会看到加载栏(正在加载:true)。

你可以在 componentWillMount() 中移动 line: this.setState({isLoading: true}) 。 因为在 componentWillMount 中设置状态不会触发组件的重新渲染。您的渲染方法将获取更新的组件。

【讨论】:

    最近更新 更多