1. 程式人生 > >前端成長之路之(四)React Hook

前端成長之路之(四)React Hook

探祕React v16.7.0-alpha Hooks
Hooks的本意是“鉤子”,在React裡就是表示一系列的特殊函式。主要閱讀了React的官網React Hook,另外還有一些其他的資料。
Hook並沒有提出一些突破性的改變,並不需要對已有的程式碼進行重構。Hook提出了一個更好的方法來結合props, state, context, refs和lifecycle。

首先,從為什麼使用Hook說起

一. It’s hard to reuse stateful logic between components
二. Complex components become hard to understand

舉例來說:元件可能會在ComponentDidMount和ComponentDidUpdate中獲取資料,同時ComponentDidMount可能會有一些不相關的邏輯,這些邏輯在ComponentDidMount中新增事件監聽,然後在componentWillUnmount中取消監聽。一起改變的相互關聯的程式碼會分離,但是毫無關係的程式碼在同一個method中結合可能會導致bug和不一致

Hooks可以基於關聯的部分將一個元件分離為多個small function,而不是根據元件的生命週期。You may also opt into managing the component’s local state with a reducer to make it more predictable.

三.Classes confuse both people and machines

React中函式和類元件之間的區別以及何時使用每個元件向來爭議很多。