为什么 StencilJS 文档建议在 componentWillLoad 中进行网络调用?

Why do StencilJS docs recommend making network calls in componentWillLoad?

我正在开发一个 Stencil JS 项目,它会进行一些网络调用以获取数据和更新状态。

在 React JS 中,网络调用将在 componentDidMount 生命周期方法中完成,而不是在 componentWillMount 方法中完成。

我很惊讶地发现 Stencil 文档中的建议几乎相反:

componentWillLoad() Called once just after the component is first connected to the DOM. Since this method is only called once, it's a good place to load data asynchronously.

在另一种情况下,Stencil 也更喜欢 componentWillLoad 而不是 componentDidLoad。它在使用 componentDidLoad 更新状态时注销控制台警告:

STENCIL: The state/prop "exampleProp" changed during "componentDidLoad()", this triggers extra re-renders, try to setup on "componentWillLoad()"

为什么 Stencil 将用户推送到 componentWillLoad 方法(渲染前),而 React 将用户推送到 componentDidMount 方法(渲染后)?

首先,我对 React 了解不多,但我看到了 componentWillMount was deprecated 以及以下解释。

There is a common misconception that fetching in componentWillMount lets you avoid the first empty rendering state. In practice this was never true because React has always executed render immediately after componentWillMount. If the data is not available by the time componentWillMount fires, the first render will still show a loading state regardless of where you initiate the fetch. This is why moving the fetch to componentDidMount has no perceptible effect in the vast majority of cases.

在 Stencil 中你可以在 componentWillLoad 中 return 一个 Promise 这将阻止组件渲染直到 Promise 已经解决(但我从来没有找到一个实际的用例).

如果您没有 return Promise,那么根据您的 render 方法(任何其他可能的渲染生命周期方法)的速度,componentDidLoad 将 运行稍晚一点,大部分时间可能是最小的(即“没有可察觉的效果”)但没有任何优势(我能想到)。

componentDidLoad 适用于必须 运行 第一次渲染后立即进行的事情。

同样,控制台警告是因为大多数时候同步修改 @State()@Prop() 属性 in componentDidLoad 是没有意义的,因为它可以通常很容易移动到更早的生命周期方法(避免在初始渲染之后重新渲染)。但也有例外,例如如果状态值取决于生成的 DOM,那么您可以忽略警告。

请注意,在某些情况下 connectedCallback 可能比 componentWillLoad 更合适,例如the clock example in Stencil's Life Cycle Methods docs.