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組件沒法靈活共享邏輯的問題。函數