背景
當你只是自己在開發的時候怎么方便怎么來,當你水平高一點的時候知道自我約束,當你成為一個小團隊管理的時候只能無奈的制定規則,放棄自由和便捷。一下內容適合團隊開發的規則制定
廢話:
React Hooks 是 React 16.8 中引入的一項新功能,它允許你在不編寫 class 組件的情況下使用 state 和其他 React 特性。通過使用 Hooks,你可以將組件的邏輯提取到可重用的函數中。React Hooks 沒有類似于 class 組件中的生命周期方法,但是你可以使用 useEffect這個 Hook 來模擬生命周期行為。
在 React Hooks 中,沒有與 class 組件中的生命周期方法完全對應的概念。但是,你可以使用
1.中級
以下是如何使用
useEffect
來模擬生命周期行為的示例:
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// 相當于 componentDidMount
useEffect(() => {
console.log('Component did mount');
return () => {
// 相當于 componentWillUnmount
console.log('Component will unmount');
};
}, []); // 空數組表示這個副作用只會在組件掛載和卸載時執行
// 相當于 componentDidUpdate
useEffect(() => {
console.log('Component did update');
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
在這個示例中,我們使用
useStateHook 來管理組件的狀態,并使用
我們使用了兩個 useEffect
Hook。第一個 useEffect
傳入了一個空數組作為依賴項,這意味著它只會在組件掛載時執行一次,類似于 componentDidMount
。同時,它返回了一個清除函數,這個函數會在組件卸載時執行,類似于 componentWillUnmount
。
第二個 useEffect
沒有傳入依賴項數組,這意味著它會在每次組件更新時執行,類似于 componentDidUpdate
。請注意,這個 useEffect
也會在組件掛載時執行一次,因為掛載也被視為一次更新。
useEffect
Hook 來處理副作用。useEffect
接受兩個參數:一個函數,以及一個可選的依賴項數組。函數中的代碼將在組件掛載和更新時執行,如果提供了依賴項數組,那么只有當數組中的值發生變化時,才會重新執行副作用。
在這個例子中,我們將文檔的標題更新為顯示點擊次數。我們將 count
作為依賴項傳遞給useEffect,這意味著只有當 count
值發生變化時,才會重新執行副作用。
注意:useEffect
函數return的匿名函數是一個可選的清除函數。這個清除函數將在組件卸載時執行,類似componentWillUnmount生命周期方法。
2.進入正題
我們當前需要考慮的是如何對高中初級的使用進行規范的約束,即使這可能會喪失Hooks 提供的更靈活、更簡潔,但是我們的整體的代碼質量和風格會在一個可控的范圍內。
可以創建自定義的 React Hooks 函數來模擬生命周期行為。以下是一個示例,展示了如何創建自定義 Hooks 來模擬
2.1. componentDidMount 和 componentWillUnmount
我們可以使用 useEffect
Hook 來模擬 componentDidMount
和 componentWillUnmount
。useEffect
接受一個函數作為參數,這個函數會在組件掛載后執行,并在組件卸載時執行清理操作。
import { useEffect } from 'react';
function useComponentDidMount(callback) {
useEffect(() => {
callback();
return () => {
// 在這里執行 componentWillUnmount 相關的操作
};
}, []); // 傳入空數組,確保 useEffect 只在掛載和卸載時執行
}
2.2. componentDidUpdate
我們可以使用useEffect
Hook 來模擬 componentDidUpdate
。useEffect
接受一個函數作為參數,這個函數會在組件掛載后以及依賴項更新時執行。
import { useEffect } from 'react';
function useComponentDidUpdate(callback, dependencies) {
useEffect(() => {
if (dependencies.length > 0) {
callback();
}
}, dependencies); // 傳入依賴項數組,確保 useEffect 在依賴項更新時執行
}
2.3. shouldComponentUpdate
我們可以使用 React.memo
和自定義比較函數來模擬 shouldComponentUpdate
。React.memo
是一個高階組件,它會對組件的 props 進行淺比較,只有在 props 發生變化時才會重新渲染組件。
import React from 'react';
function shouldComponentUpdate(Component, compareFn) {
return React.memo(Component, compareFn);
}
2.4. getDerivedStateFromProps
我們可以使用 useEffect
和 useState
Hooks 來模擬 getDerivedStateFromProps
。useEffect
會在組件掛載后以及依賴項更新時執行,我們可以在這個函數中更新 state。
import { useState, useEffect } from 'react';
function useDerivedStateFromProps(props, getDerivedState) {
const [state, setState] = useState(getDerivedState(props));
useEffect(() => {
setState(getDerivedState(props));
}, [props]);
return state;
}
2.5. getSnapshotBeforeUpdate
目前沒有直接的方法來模擬 getSnapshotBeforeUpdate
,因為函數組件沒有類似于 componentDidUpdate
的生命周期函數。但是,我們可以使用 useLayoutEffect
來在 DOM 更新之前執行一些操作。
import { useLayoutEffect } from 'react';
function useSnapshotBeforeUpdate(callback) {
useLayoutEffect(() => {
callback();
});
}
2.6 componentWillUnmount
分別模擬了 componentDidMount
import { useEffect } from 'react';
function useComponentWillUnmount(callback) {
useEffect(() => {
return () => {
callback();
};
}, []);
}
3.完整代碼如下customHooks
import { useLayoutEffect,useEffect,useMemo,useState } from 'react';
/**
*`componentDidMount` 和 `componentWillUnmount`
* callback 接受一個函數作為參數,這個函數會在組件掛載后執行,并在組件卸載時執行清理操作
*/
export function useComponentDidMount(callback,delfun=()=>{}) {
useEffect(() => {
callback();
return () => {
delfun()
// 在這里執行 componentWillUnmount 相關的操作
};
}, []); // 傳入空數組,確保 useEffect 只在掛載和卸載時執行
}
/**
*`componentDidUpdate`
* dependencies傳入依賴項數組,確保 useEffect 在依賴項更新時執行
*/
export function useComponentDidUpdate(callback, dependencies) {
useEffect(() => {
if (dependencies.length > 0) {
callback();
}
}, dependencies); // 傳入依賴項數組,確保 useEffect 在依賴項更新時執行
}
/**
*`shouldComponentUpdate`
* `React.memo`
* Component第一個參數為純函數的組件,
* compareFn第二個參數用于對比props控制是否刷新
*/
export function shouldComponentUpdate(Component, compareFn) {
return useMemo(Component, compareFn);
}
/**
*`useDerivedStateFromProps`
* props對比控制是否刷新,讓組件在 props 變化時更新 state。
* getDerivedState我們需要定義一個 `getDerivedState` 函數,它接收 `props` 作為參數,并返回一個新的狀態值
*/
export function useDerivedStateFromProps(props, getDerivedState) {
const [state, setState] = useState(getDerivedState(props));
useEffect(() => {
setState(getDerivedState(props));
}, [props]);
return state;
}
/**
*`useSnapshotBeforeUpdate`
* 在 DOM 更新之前執行一些操作。
* callback Dom更新前傳入一個處理函數
*/
export function useSnapshotBeforeUpdate(callback) {
useLayoutEffect(() => {
callback();
});
}
請注意,這些自定義 Hooks 只是模擬類組件生命周期函數的方法,并不是完全等價的替代。在某些情況下,可能需要對這些自定義 Hooks 進行調整以滿足特定需求。
現在你可以在你的組件中使用這些自定義 Hooks:
import {
shouldComponentUpdate,
useComponentDidMount,
useComponentDidUpdate,
useDerivedStateFromProps,
useSnapshotBeforeUpdate,
} from "@/customHooks";
//test useDerivedStateFromProps
const Child1 = (props) => {
function getDerivedState(props) {
console.log("child component will render");
return props.value * 2;
}
// 使用自定義的 useDerivedStateFromProps Hook
const derivedState = useDerivedStateFromProps(props, getDerivedState);
// 在這里,你可以使用 derivedState 來根據需要渲染組件或執行其他操作
return (
<div>
<p>Original value: {props.value}</p>
<p>Derived value: {derivedState}</p>
</div>
);
};
//test shouldComponentUpdate
const Child2 = (n) => {
console.log(n);
return <div>Child2{n <= 1 ? "unchange" : "changed"}</div>;
};
const App = () => {
const [count, setCount] = useState(0);
const [Vl, setVl] = useState(1);
//test componentDidMount & componentWillUnmount
useComponentDidMount(
() => {
console.log("Component did mount");
},
() => {
console.log("Component will unmount");
}
);
//test useComponentDidUpdate
useComponentDidUpdate(() => {
console.log("Component did update");
}, [count]);
// test useSnapshotBeforeUpdate
useSnapshotBeforeUpdate(() => {
console.log("useSnapshotBeforeUpdate");
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
<Child1 value={count}></Child1>
{/* test shouldComponentUpdate */}
{shouldComponentUpdate(() => Child2(count), [count])}
</div>
);
};
export default App;
小結
通過這種方式,我們可以將組件的生命周期邏輯抽離到自定義 Hooks 中,使得代碼更加清晰和可維護。
實際使用根據各個團隊情況微調后使用。
風格一向如常不喜歡說廢話,有用拿走,沒用出門右拐。