Hook简介
React Hooks是React 16.7.0-alpha版本推出的新特性,目的是解决React的状态共享问题。称之为状态共享可能描述的并不是很恰当,称为状态逻辑复用可能会更恰当,因为React Hooks只共享数据处理逻辑,并不会共享数据本身。 在React应用开发中,状态管理是组件开发必不可少的内容。以前,为了对状态进行管理,最通常的做法是使用类组件或者直接使用redux等状态管理框架。例如:
class Hook extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
You clicked {this.state.count} times
this.setState({ count: this.state.count + 1 })}>
Click me
);
}
}
现在,开发者可以直接使用React Hooks提供的State Hook来处理状态,针对那些已经存在的类组件,也可以使用State Hook很好地进行重构。例如:
import React, { useState } from 'react';
function Hook() {
const [count, setCount] = useState(0);
retu