react函数组件如何更新
React 函数组件更新方法
使用 useState Hook
通过 useState Hook 可以定义组件的状态,并触发重新渲染。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 Hook
useEffect Hook 用于处理副作用,如数据获取、订阅或手动操作 DOM。依赖项数组的变化会触发 useEffect 回调函数的执行。

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));
}, []); // 空依赖数组表示仅在组件挂载时执行
}
使用 useReducer Hook
useReducer 适用于复杂的状态逻辑,尤其是当状态更新依赖于之前的状态时。useReducer 接受一个 reducer 函数和初始状态,返回当前状态和 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 (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
}
使用 Context API
Context API 可以跨组件层级传递数据,避免 props 层层传递。结合 useContext Hook,可以订阅 Context 的变化并触发组件更新。

import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button style={{ background: theme === 'dark' ? 'black' : 'white' }}>Click me</button>;
}
使用外部状态管理库
对于大型应用,可以使用外部状态管理库如 Redux、MobX 或 Zustand。这些库提供更强大的状态管理能力,并与 React 深度集成。
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
function Counter() {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
</div>
);
}
强制更新
在极少数情况下,可能需要强制组件重新渲染。可以通过改变组件的 key 属性或使用 useState 强制更新。
import React, { useState } from 'react';
function ForceUpdateExample() {
const [, forceUpdate] = useState();
return (
<div>
<button onClick={() => forceUpdate({})}>Force Update</button>
</div>
);
}






