探秘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中函数和类组件之间的区别以及何时使用每个组件向来争议很多。