1. 程式人生 > >Formik官方應用案例解析(四)組件生命周期事件

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

ext discus side all trac mount prop use 新的

基礎

示例工程: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

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