自定義Hook本質(zhì)上只是一種函數(shù)代碼邏輯的抽取,嚴(yán)格意義上來(lái)說(shuō),它本身并不算React的特性啄寡。
舉個(gè)例子:
需求:所有的組件在創(chuàng)建和銷(xiāo)毀時(shí)都進(jìn)行打印哩照;
- 組件被創(chuàng)建:打印挺物,組件被創(chuàng)建了;
- 組件被銷(xiāo)毀:打印飘弧,組件被銷(xiāo)毀了识藤;
分析:如果對(duì)每個(gè)組件都搞一個(gè)useEffect來(lái)控制,未免也太繁瑣了次伶;這時(shí)候我們需要對(duì)復(fù)用的代碼邏輯進(jìn)行抽取痴昧。
注意:在普通function中不能使用hooks;這時(shí)候冠王,我們自定義hook名稱(chēng)以u(píng)se開(kāi)頭赶撰,變成了useLoggingLife,就可以在其中用hooks了。
import React, { useEffect } from 'react'
const Home = (props) => {
useLoggingLife("Home");
return <h2>Home</h2>
}
const Profile = (props) => {
useLoggingLife("Profile");
return <h2>Profile</h2>
}
export default function CustomLifeHookDemo01() {
useLoggingLife("CustomLifeHookDemo01")
return (
<div>
<h2>CustomLifeHookDemo1</h2>
<Home />
<Profile />
</div>
)
}
function useLoggingLife(name) {
useEffect(() => {
console.log(`${name}組件被創(chuàng)建出來(lái)了`);
return () => {
console.log(`${name}組件被銷(xiāo)毀掉了`);
}
}, [])
}
抽離可復(fù)用代碼
import React from 'react'
import useUserContext from '../hooks/user-hook';
export default function CustomContextShareHook() {
const [user, token] = useUserContext();
console.log(user, token);
return (
<div>
<h2>CustomContextShareHook</h2>
</div>
)
}
// user-hook
import { useContext } from "react";
import { UserContext, TokenContext } from "../App";
function useUserContext() {
const user = useContext(UserContext);
const token = useContext(TokenContext);
return [user, token]
}
export default useUserContext;