为什么 React 文档建议在 componentDidMount 而不是 componentWillMount 中执行 AJAX?
我理解为什么 componentDidMount
适用于需要访问 DOM 的任何内容,但 AJAX 请求不一定或通常需要这样做.
I understand why componentDidMount
is appropriate for anything that requires DOM access, but an AJAX request doesn’t necessarily or usually need this.
是什么?
componentDidMount
用于副作用.添加事件侦听器、AJAX、改变 DOM 等.
componentDidMount
is for side effects. Adding event listeners, AJAX, mutating the DOM, etc.
componentWillMount
很少有用;特别是如果您关心服务器端渲染(添加事件侦听器会导致错误和泄漏,以及许多其他可能出错的东西).
componentWillMount
is rarely useful; especially if you care about server side rendering (adding event listeners causes errors and leaks, and lots of other stuff that can go wrong).
有关于从类组件中删除 componentWillMount
的讨论,因为它与构造函数的用途相同.它将保留在 createClass
组件上.
There is talk about removing componentWillMount
from class components since it serves the same purpose as the constructor. It will remain on createClass
components.