加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Formik官方应用案例解析(四)组件生命周期事件

发布时间:2020-12-15 06:24:17 所属栏目:百科 来源:网络整理
导读:基础 示例工程:formik-09x-component-lifecycle-events-example 核心文件:index.js 示例说明 Formik大部分示例工程中都使用了极其方式创建Formik表单组件,本示例中则使用了复杂(或者说典型)方式创建一个Formik表单组件,即使用其继承自React.Component

基础

示例工程:formik-09x-component-lifecycle-events-example
核心文件:index.js

示例说明

Formik大部分示例工程中都使用了极其方式创建Formik表单组件,本示例中则使用了复杂(或者说典型)方式创建一个Formik表单组件,即使用其继承自React.Component组件,从而展示有关生命周期事件的基本使用。但是,也比较简单,只涉及到了两个事件:


  • componentWillReceiveProps

  • render


但是,这个示例中使用的componentWillReceiveProps事件在最新的React中已经过时。引用一个老外的话说是:

This lifecycle,however,is on the deprecation path; it will stop working as-named in React 17: https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops

Given that,we should provide a more future-friendly solution for listening for shallow route changes. Perhaps adding a popstate listener in componentDidMount. If that seems like the best option I can add it to docs,but opening this ticket for discussion/tracking.

现在,在最新版本React环境下需要使用UNSAFE_componentWillReceiveProps()来代替。

另外:在新版本中,官方明确指出使用上述事件容易导致一些复杂BUG的出现,所以官方建议使用事件来代替。另外,还有如下建议:

Note:

Using this lifecycle method often leads to bugs and inconsistencies,and for that reason it is going to be deprecated in the future.

If you need to perform a side effect (for example,data fetching or an animation) in response to a change in props,use componentDidUpdate lifecycle instead.

For other use cases,follow the recommendations in this blog post about derived state.

If you used componentWillReceiveProps for re-computing some data only when a prop changes,use a memoization helper instead.

If you used componentWillReceiveProps to “reset” some state when a prop changes,consider either making a component fully controlled or fully uncontrolled with a key instead.

In very rare cases,you might want to use the getDerivedStateFromProps lifecycle as a last resort.

引用

1,https://github.com/zeit/next.js/issues/4154

2,https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读