React Hooks 是 React 16.8 版本引入的一個新特性,它允許你在不編寫類(class)的情況下使用 state 和其他 React 特性。以下是一些常用的 React Hooks API 及其使用技巧:
useState
是一個讓函數組件可以使用 state 的 Hook。
使用技巧:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(prevCount => prevCount + 1);
};
return (
<div>
<p>You clicked {count} times</p>
<button onClick={increment}>Click me</button>
</div>
);
}
useEffect
是一個讓函數組件可以使用副作用(如數據獲取、訂閱、手動修改 DOM 等)的 Hook。
使用技巧:
useEffect
的第二個參數是一個依賴數組,只有當數組中的值發生變化時,副作用才會重新執行。[]
),副作用只會在組件掛載和卸載時執行。import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
useContext
是一個讓函數組件可以使用 React context 的 Hook。
使用技巧:
useContext
,無需使用 Consumer
組件。import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button className={theme}>I am styled by theme context!</button>;
}
useReducer
是一個讓函數組件可以使用更復雜 state 邏輯的 Hook。
使用技巧:
useReducer
接受一個 reducer 函數和一個初始 state,返回當前的 state 和一個 dispatch 函數。import React, { useReducer } from 'react';
function 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 Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
</>
);
}
useCallback
是一個返回記憶化回調函數的 Hook。
使用技巧:
useCallback
返回的函數才會重新創建。import React, { useCallback, useState } from 'react';
function ParentComponent() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount(c => c + 1);
}, [setCount]);
return <ChildComponent onIncrement={increment} />;
}
useMemo
是一個返回記憶化值的 Hook。
使用技巧:
useMemo
返回的值才會重新計算。import React, { useMemo, useState } from 'react';
function ExpensiveComponent({ list }) {
const [filter, setFilter] = useState('');
const filteredList = useMemo(() => {
return list.filter(item => item.includes(filter));
}, [list, filter]);
return (
<div>
<input value={filter} onChange={e => setFilter(e.target.value)} />
{filteredList.map(item => <p key={item}>{item}</p>)}
</div>
);
}
useRef
是一個返回可變的 ref 對象的 Hook。
使用技巧:
useRef
返回的對象在組件的整個生命周期內保持不變。import React, { useRef } from 'react';
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` 指向已掛載到 DOM 上的文本輸入元素
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
自定義 Hooks 是一個讓你能夠提取組件邏輯到可重用函數的 Hook。
使用技巧:
use
開頭,以便與 React 提供的內置 Hooks 區分開來。import React, { useState, useEffect } from 'react';
function useCustomHook() {
const [data, setData] = useState(null);
useEffect(() => {
fetchData().then(fetchedData => setData(fetchedData));
}, []);
return data;
}
function MyComponent() {
const data = useCustomHook();
return <div>{data}</div>;
}
通過合理使用這些 Hooks,你可以編寫出更加簡潔、高效和易于維護的 React 組件。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。