React 知识速查表
本页面汇总了 React 编程中最常用的语法和知识点,方便快速查阅。
核心概念
| 概念 | 说明 |
|---|---|
| 组件 | UI 的独立可复用构建块 |
| JSX | JavaScript 的语法扩展,用于描述 UI |
| Props | 父组件传递给子组件的数据 |
| State | 组件内部的响应式数据 |
| 虚拟 DOM | React 维护的轻量 DOM 副本 |
实时编辑器
const Welcome = ({ name = "访客" }) => ( <div style={{ padding: '10px', border: '1px solid #6366f1', borderRadius: '4px' }}> <h2 style={{ margin: 0, color: '#6366f1' }}>Hello, {name}!</h2> <p style={{ margin: '5px 0 0' }}>这是一个最简洁的箭头函数组件。</p> </div> );
结果
Loading...
常用 Hooks 速查
useState - 状态管理
const [state, setState] = useState(initialValue);
setState(newValue); // 直接设置
setState(prev => prev + 1); // 函数式更新
useEffect - 副作用处理
useEffect(() => {
// 副作用逻辑
return () => {}; // 清理函数
}, [dependencies]); // 依赖数组
// 常用模式
useEffect(() => {}, []); // 挂载时执行一次
useEffect(() => {}, [dep]); // dep 变化时执行
useEffect(() => {}); // 每次渲染执行(谨慎使用)
useContext - 上下文访问
const value = useContext(MyContext);
useRef - 引用
const ref = useRef(initialValue);
ref.current // 访问或修改值
// DOM 引用
<input ref={inputRef} />
inputRef.current.focus();
useMemo / useCallback - 性能优化
const value = useMemo(() => compute(), [deps]);
const fn = useCallback(() => {}, [deps]);
useReducer - 复杂状态管理
const [state, dispatch] = useReducer(reducer, initialArg, init?);
function reducer(state, action) {
switch (action.type) {
case 'increment': return { count: state.count + 1 };
default: return state;
}
}
dispatch({ type: 'increment', payload: value });
useLayoutEffect - 布局副作用
useLayoutEffect(() => {
// 在浏览器绘制前执行
// 用于 DOM 测量
}, [deps]);
useTransition - 非阻塞更新
const [isPending, startTransition] = useTransition();
startTransition(() => {
setState(newValue); // 标记为低优先级更新
});
useDeferredValue - 延迟值
const deferredValue = useDeferredValue(value);
// deferredValue 会"滞后"于 value
useId - 唯一 ID
const id = useId(); // 生成唯一 ID
<input id={id} />
useImperativeHandle - 暴露方法
const MyComponent = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
focus: () => inputRef.current.focus()
}));
});
React 19 新 Hooks
useActionState - 表单 Action 状态
import { useActionState } from 'react';
const [state, formAction, isPending] = useActionState(
async (prevState, formData) => {
// 处理表单提交
const result = await submitForm(formData);
return result; // 返回的状态会作为新的 state
},
null // 初始状态
);
// 在表单中使用
<form action={formAction}>
<input name="field" />
<button disabled={isPending}>提交</button>
{state?.error && <p>{state.error}</p>}
</form>
useOptimistic - 乐观更新
import { useOptimistic } from 'react';
function TodoList({ todos }) {
const [optimisticTodos, setOptimisticTodo] = useOptimistic(
todos,
(state, newTodo) => [...state, newTodo]
);
async function addTodo(text) {
setOptimisticTodo({ id: Date.now(), text }); // 乐观添加
await saveTodo(text); // 实际保存
}
return <ul>{optimisticTodos.map(t => <li key={t.id}>{t.text}</li>)}</ul>;
}
use - 读取资源
import { use } from 'react';
// 读取 Promise
function Comments({ promise }) {
const comments = use(promise); // 暂停直到 Promise 解析
return comments.map(c => <p key={c.id}>{c.text}</p>);
}
// 读取 Context(可在条件中调用)
function Heading({ show, children }) {
if (!show) return null;
const theme = use(ThemeContext); // 条件中使用
return <h1 style={{ color: theme.color }}>{children}</h1>;
}
useFormStatus - 表单状态
import { useFormStatus } from 'react-dom';
function SubmitButton() {
const { pending, data, method } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? '提交中...' : '提交'}
</button>
);
}
Hooks 规则
// ❌ 错误:条件中调用
if (condition) {
const [value, setValue] = useState(0);
}
// ❌ 错误:循环中调用
for (let i = 0; i < items.length; i++) {
const [value, setValue] = useState(items[i]);
}
// ✅ 正确:顶层调用
function Component() {
const [value, setValue] = useState(0);
}
条件渲染
// 三元运算符
{isLoggedIn ? <User /> : <Login />}
// 逻辑与 &&
{show && <Component />}
// switch
{status === 'loading' && <Loading />}
{status === 'error' && <Error />}
{status === 'success' && <Success />}
列表渲染
function List({ items }) {
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
事件处理
function Button() {
const handleClick = (e) => {
e.preventDefault();
console.log('点击');
};
return <button onClick={handleClick}>点击</button>;
}
表单处理
function Form() {
const [value, setValue] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
console.log(value);
};
return (
<form onSubmit={handleSubmit}>
<input
value={value}
onChange={e => setValue(e.target.value)}
/>
<button type="submit">提交</button>
</form>
);
}
常用 API
| API | 说明 |
|---|---|
React.memo() | 高阶组件,记忆组件 |
React.forwardRef() | 转发 ref |
React.createPortal() | 传送门,渲染到其他 DOM 节点 |
React.Fragment | 片段,避免额外 DOM 节点 |
React.StrictMode | 严格模式,开发检查 |
React.Suspense | 悬念,处理异步加载 |
React.lazy() | 懒加载组件 |
高级特性
Portals
import { createPortal } from 'react-dom';
function Modal({ children }) {
return createPortal(
<div className="modal">{children}</div>,
document.body
);
}
Error Boundary
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.error(error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>出错了</h1>;
}
return this.props.children;
}
}
Suspense 与懒加载
import { Suspense, lazy } from 'react';
const Dashboard = lazy(() => import('./Dashboard'));
function App() {
return (
<Suspense fallback={<Loading />}>
<Dashboard />
</Suspense>
);
}
生命周期对照表
| 类组件方法 | 函数组件等效 |
|---|---|
| constructor | useState 初始化 |
| componentDidMount | useEffect(() => , []) |
| componentDidUpdate | useEffect(() => , [deps]) |
| componentWillUnmount | useEffect return 清理函数 |
| shouldComponentUpdate | React.memo |
| getDerivedStateFromProps | 更新时设置 state |
| getSnapshotBeforeUpdate | useLayoutEffect |
| componentDidCatch | Error Boundary 类组件 |
状态管理方案
| 方案 | 适用场景 |
|---|---|
| useState | 局部状态 |
| useReducer | 复杂状态逻辑 |
| useContext | 全局状态 |
| Redux | 大型应用 |
| Zustand | 轻量级状态管理 |
| Jotai | 原子化状态 |
| React Query | 服务端状态 |
React Router
import { BrowserRouter, Routes, Route, Link, useNavigate, useParams } from 'react-router-dom';
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/users/:id" element={<User />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
// 编程式导航
const navigate = useNavigate();
navigate('/path');
// 路由参数
const { id } = useParams();
性能优化清单
- 使用
React.memo()避免不必要的重渲染 - 使用
useMemo()缓存计算结果 - 使用
useCallback()缓存函数 - 使用稳定的
key帮助 React 识别元素 - 代码分割(React.lazy + Suspense)
- 虚拟列表处理大数据
- 合理使用 useEffect 依赖数组
- 避免在渲染中创建新对象/函数
CSS 方案
| 方案 | 说明 |
|---|---|
| CSS Modules | 模块化 CSS |
| Styled Components | CSS-in-JS |
| Tailwind CSS | Utility-First CSS |
| 内联样式 | style=\{\{ color: 'red' \}\} |
TypeScript 常用类型
// Props 类型
interface Props {
name: string;
age?: number;
onClick: () => void;
children: React.ReactNode;
}
// 函数组件
function Component({ name }: Props) {
return <div>{name}</div>;
}
// useState 类型
const [count, setCount] = useState<number>(0);
// useRef 类型
const ref = useRef<HTMLInputElement>(null);
// 事件类型
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {};
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {};
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {};
常用库
| 库 | 用途 |
|---|---|
| react-router-dom | 路由 |
| axios | HTTP 请求 |
| react-query | 服务端状态管理 |
| react-hook-form | 表单处理 |
| zustand | 轻量状态管理 |
| react-window | 虚拟列表 |
| framer-motion | 动画 |
调试技巧
// 使用 React DevTools
// Chrome 扩展:React Developer Tools
// 控制台调试
useEffect(() => {
console.log('状态变化:', state);
}, [state]);
// 使用 useRef 追踪渲染次数
const renderCount = useRef(0);
renderCount.current++;
console.log('渲染次数:', renderCount.current);