为什么不推荐使用 componentWillReceiveProps? [英] why is componentWillReceiveProps deprecated?

查看:126
本文介绍了为什么不推荐使用 componentWillReceiveProps?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通读了 https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#fetching-external-data-when-props-change.我仍然无法理解为什么他们必须弃用 componentWillReceiveProps.
在 componentWillReceiveProps 中进行 ajax 调用有什么危害?一旦 ajax 调用返回值,我就会更新状态从而重新渲染组件.

I read through https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#fetching-external-data-when-props-change . I am still not able to understand why did they have to deprecate componentWillReceiveProps.
What was the harm in making an ajax call inside componentWillReceiveProps? Once ajax call returns the value , I update the state thereby rerendering the component.

推荐答案

componentWillReceiveProps 是一个 同步 钩子.在此钩子中调用异步函数(如数据获取)将需要在设置新 props 和数据加载完成之间进行渲染.

componentWillReceiveProps is a synchronous hook. Calling asynchronous function like data fetching inside this hook will need to render in between when the new props are set and when data has finished loading.

但是 getDerivedStateFromProps 是一个 异步 钩子,不需要任何额外的渲染.因此,componentWillReceiveProps 被弃用,原因如下:

But the getDerivedStateFromProps is an asynchronous hook won't require any additional render. Thus, componentWillReceiveProps is being deprecated in favor of the following reason:

  1. 使用 getDerivedStateFromProps
  2. 或者,使用 componentDidUpdate

这不会给你不必要的渲染.请注意,getDerivedStateFromProps 仅在极少数情况下使用.所以,我建议你尽量使用 componentDidUpdate 钩子.

Which won't give you unnecessary renders. Note that getDerivedStateFromProps is used only in rare case though. So, I suggest you to use componentDidUpdate hook as far as possible.

在比较 componentWillMount 和 componentDidMount 时会发生类似的事情.每当您需要操作异步操作并在任何情况下忘记 componentWillMount 时,请使用 componentDidMount.关于 componentDidMount 的更多解释在我的另一篇帖子中.

The similar things happen when comparing componentWillMount and componentDidMount. Use componentDidMount whenever you need operate async operation and forget componentWillMount at all condition. More explanation about componentDidMount is here in my another post.

这篇关于为什么不推荐使用 componentWillReceiveProps?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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