React Hooks 是 React 16.8 版本引入的一項嚴重特點,它使得函數組件可能擁有類組件的才能,如狀況管理、生命周期等。經由過程利用 Hooks,開辟者可能更高效地編寫組件,進步代碼的可讀性跟可保護性。本文將具體介紹 React Hooks 的核心 API,幫助開辟者輕鬆控制其利用技能。
一、useState:管理組件狀況
useState
是 React Hooks 中最基本的鉤子,用於在函數組件中增加狀況。
利用方法:
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
注意事項:
useState
只能在函數組件的最頂層利用。useState
前去一個數組,其中包含以後狀況的值跟一個更新狀況的函數。
二、useEffect:處理反感化
useEffect
用於在函數組件中履行反感化操縱,如發送 AJAX 懇求、訂閱變亂等。
利用方法:
import React, { useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // 依附項數組
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
注意事項:
useEffect
前去一個清理函數,用於撤消反感化。useEffect
的依附項數組中,只有當依附項產生變更時,反感化才會重新履行。
三、useContext:花費高低文
useContext
用於在函數組件中花費 React 高低文(Context)。
利用方法:
import React, { useContext } from 'react';
import MyContext from './MyContext';
function Example() {
const theme = useContext(MyContext);
return (
<div>
<h1>Theme: {theme}</h1>
</div>
);
}
注意事項:
useContext
只能用於花費那些曾經經由過程React.createContext
創建的高低文。
四、useReducer:管理複雜狀況
useReducer
用於在函數組件中管理複雜的狀況。
利用方法:
import React, { useReducer } from 'react';
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
};
function Example() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
<p>You clicked {state.count} times</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
}
注意事項:
useReducer
實用於管理複雜的狀況邏輯。useReducer
的狀況更新函數reducer
應當是純函數。
五、useCallback:緩存回調函數
useCallback
用於緩存回調函數,避免在每次襯著時都創建新的函數。
利用方法:
import React, { useCallback } from 'react';
function Example() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount(count + 1);
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={increment}>Increment</button>
</div>
);
}
注意事項:
useCallback
的依附項數組中,只有當依附項產生變更時,緩存的回調函數才會更新。
六、useMemo:緩存打算成果
useMemo
用於緩存打算成果,避免在每次襯著時都停止重複打算。
利用方法:
import React, { useMemo } from 'react';
function Example() {
const [count, setCount] = useState(0);
const memoizedValue = useMemo(() => computeExpensiveValue(count), [count]);
return (
<div>
<p>You clicked {count} times</p>
<p>Memoized value: {memoizedValue}</p>
</div>
);
}
function computeExpensiveValue(count) {
// 模仿打算過程
for (let i = 0; i < 1000000000; i++) {}
return count;
}
注意事項:
useMemo
的依附項數組中,只有當依附項產生變更時,緩存的值才會更新。
七、useRef:創建可變的引用東西
useRef
用於創建一個可變的引用東西,其 .current
屬性可能被重新賦值。
利用方法:
import React, { useRef } from 'react';
function Example() {
const inputEl = useRef(null);
const focusInput = () => {
inputEl.current.focus();
};
return (
<div>
<input ref={inputEl} type="text" />
<button onClick={focusInput}>Focus the input</button>
</div>
);
}
注意事項:
useRef
前去的引用東西在組件的全部生命周期內保持穩定。
八、自定義 Hooks
自定義 Hooks 容許你封裝可重用的邏輯,使其可能在多個組件之間共享。
利用方法:
import React, { useState, useEffect } from 'react';
function useCounter(initialCount) {
const [count, setCount] = useState(initialCount);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
return [count, setCount];
}
function Example() {
const [count, setCount] = useCounter(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
注意事項:
- 自定義 Hooks 應當以
use
掃尾。 - 自定義 Hooks 可能接收參數,並前去多個值。
總結
React Hooks 為函數組件供給了富強的功能,使得開辟者可能更高效地編寫組件。經由過程控制上述核心 Hooks 的利用技能,開辟者可能輕鬆應對各種複雜的組件開辟場景。