寫在前面:一個讓React老手都拍案叫絕的魔法
“等等,函數組件怎么能有狀態?!” —— 這是2018年我第一次聽說React Hooks時的反應。當時我正在用class組件寫一個復雜的表單,生命周期方法亂得像一碗意大利面。直到我看到了這段代碼:
function Counter() {const [count, setCount] = useState(0);useEffect(() => {document.title = `你點擊了${count}次`;});return (<div><p>當前計數: {count}</p><button onClick={() => setCount(count + 1)}>點我啊!</button></div>);
}
短短十幾行代碼,完成了以前需要幾十行class組件才能實現的功能。沒有this,沒有生命周期方法,代碼簡潔得令人發指。這到底是怎么做到的?函數組件憑什么突然這么強大了?帶著這些疑問,我開始了Hooks的探索之旅…
一、Hooks為何讓整個React社區為之瘋狂?
1.1 那些年,我們被class折磨的日子
記得剛學React時,光是一個簡單的組件就要寫一堆樣板代碼:
class MyComponent extends React.Component {constructor(props) {super(props);this.state = { count: 0 };this.handleClick = this.handleClick.bind(this);}componentDidMount() { /*...*/ }componentDidUpdate() { /*...*/ }componentWillUnmount() { /*...*/ }handleClick() {this.setState({ count: this.state.count + 1 });}render() {return <button onClick={this.handleClick}>{this.state.count}</button>;}
}
光是綁定this就能讓新手崩潰三次,更別提生命周期方法的復雜關系了。Hooks的出現,就像是在React世界里突然出現了一道光。
1.2 Hooks帶來的三大革命性改變
- 代碼量銳減:同樣的功能,代碼量能減少30%-50%
- 邏輯復用革命:再也不用忍受HOC和render props的嵌套地獄
- 學習曲線降低