react如何管理状态
状态管理的基本概念
在React中,状态(state)是组件内部的数据,用于动态更新UI。状态可以是局部状态(组件内部)或全局状态(跨组件共享)。
使用useState管理局部状态
useState是React Hooks提供的函数,适用于组件内部的状态管理。
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>
);
}
count是状态变量,setCount是更新函数。每次调用setCount会触发组件重新渲染。
使用useReducer管理复杂状态
对于逻辑复杂的状态,useReducer提供更结构化的方式。

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>
);
}
reducer函数根据不同的action.type更新状态,适合多操作场景。
使用Context API共享全局状态
Context允许跨组件传递数据,避免逐层传递props。
import React, { createContext, useContext, useState } from 'react';
const CountContext = createContext();
function CountProvider({ children }) {
const [count, setCount] = useState(0);
return (
<CountContext.Provider value={{ count, setCount }}>
{children}
</CountContext.Provider>
);
}
function Counter() {
const { count, setCount } = useContext(CountContext);
return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}
function App() {
return (
<CountProvider>
<Counter />
</CountProvider>
);
}
CountProvider包裹需要共享状态的组件,子组件通过useContext访问状态。

使用第三方库管理全局状态
Redux和Zustand是流行的状态管理库,适用于大型应用。
Redux示例
import { createStore } from 'redux';
import { Provider, useSelector, useDispatch } from 'react-redux';
const initialState = { count: 0 };
function reducer(state = initialState, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
default:
return state;
}
}
const store = createStore(reducer);
function Counter() {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
return (
<button onClick={() => dispatch({ type: 'increment' })}>
Count: {count}
</button>
);
}
function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}
Redux通过单一存储(store)和纯函数(reducer)管理状态。
Zustand示例
import create from 'zustand';
const useStore = create(set => ({
count: 0,
increment: () => set(state => ({ count: state.count + 1 })),
}));
function Counter() {
const { count, increment } = useStore();
return <button onClick={increment}>Count: {count}</button>;
}
Zustand提供更简洁的API,无需Provider包裹组件。
状态管理选择建议
- 简单组件:
useState或useReducer。 - 跨组件共享:
Context API或第三方库(如Redux/Zustand)。 - 大型应用:Redux(强类型)或Zustand(轻量级)。






