Hook的寫法,可以把Class的寫法改成純函式行表達,把React變成更純粹,更乾淨,但只適合用於比較不複雜的Component來寫。
需要嚴謹的對生命週期做操作,且高頻率碰到 閉包問題的,就可以改回本來Class的寫法會更好。
這邊Update 語法雖然可以代替,但有很嚴重的不一樣,在useEffect 在state都沒變化的情況下,就算沒設條件,都還是不會立刻更新。
而componentDidUpdate 是不管怎麼樣,動到state或props,管你有沒有變更值,一樣會重新觸發render,而 useEffect比較聰明不會。
useEffect(() => { // componentDidMount }, []); useEffect(() => { // componentDidUpdate if( name!= previousState) return () => { // componentWillUnmount }; }, [name]); //if( name!= previousState)
原本
class App extends React.Component { constructor(props) { super(props); this.state = { name: "湯姆貓" }; this.action = null; } componentDidMount() { this.action = "準備抓貓"; } componentDidUpdate() { this.action = "抓貓"; } componentWillUnmount() { this.action = "休息"; } render() { return ( <div> {this.state.name} <button onClick={() => this.setState({ name: "壞貓咪" })}>按我</button> <button onClick={() => alert("狀態: " + this.action)}>狀態</button> </div> ); } }
改寫
const App = () => { const [name, setName] = useState("湯姆貓"); let action = null; useEffect(() => { action = "準備抓貓"; }, []); useEffect(() => { action = "抓貓"; return () => { action = "休息"; }; }); return ( <div> {name} <button onClick={() => setName("臭老鼠")}>按我</button> <button onClick={() => alert("狀態: " + action)}>狀態</button> </div> ); }; ReactDOM.render(<App />, document.getElementById("app"));
合體
import React, { useState, useEffect } from "react"; import ReactDOM from "react-dom"; class App extends React.Component { constructor(props) { super(props); this.state = { name: "湯姆貓" }; this.action = null; } componentDidMount() { console.log("準備抓貓"); this.action = "準備抓貓"; } componentDidUpdate() { console.log("抓貓"); this.action = "抓貓"; } componentWillUnmount() { console.log("休息"); this.action = "休息"; } render() { return ( <div> {this.state.name} <button onClick={() => this.setState({ name: "壞貓咪" })}>按我</button> <button onClick={() => alert("狀態: " + this.action)}>狀態</button> <UseStateHook /> </div> ); } } const UseStateHook = () => { const [name, setName] = useState("傑立鼠"); let action = null; useEffect(() => { console.log("準備躲貓"); action = "準備躲貓"; }, []); useEffect(() => { console.log("跑啊"); action = "跑啊"; return () => { console.log("躲起來"); action = "躲起來"; }; }); return ( <div> {name} <button onClick={() => setName("臭老鼠")}>按我</button> <button onClick={() => alert("狀態: " + action)}>狀態</button> </div> ); }; ReactDOM.render(<App />, document.getElementById("app"));
@copyright MRcodingRoom
觀看更多文章請點MRcoding筆記
觀看更多文章請點MRcoding筆記