React Hooks 完全指南
React Hooks 彻底改变了我们编写 React 组件的方式。本文将深入探讨 Hooks 的核心概念和最佳实践。
useState Hook
最基础也是最常用的 Hook:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
useEffect Hook
处理副作用的强大工具:
import { useEffect, useState } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('/api/data')
.then(res => res.json())
.then(setData);
}, []); // 空依赖数组表示只在组件挂载时执行
return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
}
自定义 Hooks
创建可复用的逻辑:
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
return initialValue;
}
});
const setValue = (value) => {
try {
setStoredValue(value);
window.localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error(error);
}
};
return [storedValue, setValue];
}
总结
React Hooks 提供了一种更简洁、更灵活的方式来管理组件状态和副作用。掌握这些概念将大大提升你的 React 开发效率。