Hooks 是一项新功能提案,可以让您在不编写类的状况下使用 state(状态) 和其余 React 功能。它们目前处于 React v16.7.0-alpha 中,并在 一个开放RFC 中进行讨论。html
最近团队有项目开始使用了React Hooks。虽然我没参与其中,但空闲之余阅读了一下官方概述,不由佩服react团队又为前端开发带来了崭新的概念。前端
为了组件状态逻辑复用。咱们通常会使用高阶组件,经过props传递数据。(再这里先不讨论render-props)react
<WithHoc1>
<WithHoc2>
<WithHoc3>
<MyApp id="myId"/>
</WithHoc3>
</WithHoc2>
</WithHoc1>
复制代码
function useHoc1(myId) {
const [hoc1, setHoc1] = useState(0);
// 根据myId 去setHoc1
return hoc1;
}
// 其余 function
function MyApp(myId) {
hoc1 = useHoc1(myId);
hoc2 = useHoc2(myId);
hoc3 = useHoc3(myId);
// 可返回jsx或任意值
}
复制代码
直接拿官方事例:这是一个 React 计数器的 class 组件。它在 React 对 DOM 进行操做以后,当即更新了 document 的 title 属性bash
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
复制代码
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
复制代码
使用React Hooks后,有了useState摆脱了React组件类中的state,useEffect摆脱了React组件类生命周期。咱们终于能够轻松用纯函数方式去实现组件,而且解决了React组件没法灵活共享逻辑的问题。函数