react hooks如何用
React Hooks 的基本用法
React Hooks 是 React 16.8 引入的特性,允许在函数组件中使用状态和其他 React 特性。以下是几种常用 Hooks 的用法:
useState
useState 用于在函数组件中添加状态管理。它返回一个状态值和一个更新状态的函数。
import React, { 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
useEffect 用于处理副作用,如数据获取、订阅或手动 DOM 操作。它可以替代类组件中的 componentDidMount、componentDidUpdate 和 componentWillUnmount。

import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []); // 空数组表示仅在组件挂载时执行
return <div>{data ? data.message : 'Loading...'}</div>;
}
useContext
useContext 用于访问 React 的 Context,避免多层传递 props。
import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button style={{ background: theme === 'dark' ? '#333' : '#eee' }}>Themed Button</button>;
}
useReducer
useReducer 是 useState 的替代方案,适用于复杂状态逻辑。

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 (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
);
}
自定义 Hooks
可以创建自定义 Hooks 来复用状态逻辑。自定义 Hook 是一个以 use 开头的函数,可以调用其他 Hooks。
import { useState, useEffect } from 'react';
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}
function WindowWidthDisplay() {
const width = useWindowWidth();
return <div>Window width: {width}px</div>;
}
Hooks 的规则
使用 Hooks 时需要遵循以下规则:
- 只在 React 函数组件或自定义 Hooks 中调用 Hooks。
- 不要在循环、条件或嵌套函数中调用 Hooks,确保 Hooks 的调用顺序一致。
Hooks 提供了一种更简洁的方式来编写 React 组件,同时保留了 React 的核心概念。通过合理使用 Hooks,可以显著减少代码量并提高可维护性。






