React Hook First Met
官方文档中介绍React Hook, 将他描述为一种新特性,能让你在不使用class的情况下使用state以及其他React特性。
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
可以说React Hook的出现, 赋予了Function Component一系列的能力, 使其能够与Class Component 相提并论
Function Component & Class Component
Function components capture the rendered values.
举个栗子:
Function component
function ProfilePage(props) {
const showMessage = () => {
alert('Followed ' + props.user);
};
const handleClick = () => {
setTimeout(showMessage, 3000);
};
return (
<button onClick={handleClick}>Follow</button>
);
}
Class component
class ProfilePage extends React.Component {
showMessage = () => {
alert('Followed ' + this.props.user);
};
handleClick = () => {
setTimeout(this.showMessage, 3000);
};
render() {
return <button onClick={this.handleClick}>Follow</button>;
}
}
看看效果 CodeSandbox
为什么在Function Component中点击Follow后改变user的值,弹出框任然显示的是出发Follow时的值?原因很简单, Props are Read-Only. React官方文档Components and Props章节中有这么一句话。
Whether you declare a component as a function or a class, it must never modify its own props.
那为什么Class Component中的user值有发生了改变呢?props不是不会改变的吗?对比一下两边的写法
// Class Component
showMessage = () => {
alert('Followed ' + this.props.user);
};
// Function Component
const showMessage = () => {
alert('Followed ' + props.user);
};
对于Class Component, 发生改变的是上下文this, 当下拉框的选中值发生改变, 上下文对象this发生改变, 从而导致showMessage在调用的时候 this.props.user 的值发生了改变。
Original intention
React Hook 的产生主要是为了解决什么问题呢?下面几点是由Dan Abramov在2018年React Conf上提出的。
1、嵌套地狱
在组件之间复用状态逻辑很难, 生命周期函数中充斥着各种状态和逻辑。如果使用高阶或render props 很容易造成难以理解的嵌套地狱。
2、庞大的组件
对于包含复杂业务的组件,业务逻辑难以拆分,导致单个组件的体积过于庞大
3、难以理解的class
- this指针指向不明
- class不能很好的压缩
- class 在热重载时会出现不稳定的情况
Hook Api
Hook Api的使用方法可以直接上官方文档 Hooks学习,这里也有一个自己写的例子可以看一下各个Api怎么使用的,同时能做写什么 有意思 的事,代码中 有详细的注释 解释api的用法
在线Demo: CodeSandbox
关于原理部分,我会在用一篇文章尽可能清楚的描述Hooks是如何赋予函数组件与React Class Component一样的能力;