react如何创建一个状态仓库
使用 useState 创建组件内部状态
在 React 中,最简单的状态管理方式是使用 useState Hook。适用于组件内部的局部状态管理。
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>
);
}
使用 useReducer 管理复杂状态
当状态逻辑较复杂时,useReducer 更适合。它通过 reducer 函数集中处理状态更新。
import React, { useReducer } from 'react';
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
default:
return state;
}
};
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
</div>
);
}
使用 Context API 实现全局状态
对于跨组件的状态共享,可以通过 createContext 和 useContext 实现轻量级全局状态管理。
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 (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
function App() {
return (
<CountProvider>
<Counter />
</CountProvider>
);
}
使用第三方库(如 Redux、Zustand)
对于大型应用,推荐使用专业状态管理库:
Redux 示例
import { createStore } from 'redux';
import { Provider, useSelector, useDispatch } from 'react-redux';
const store = createStore((state = { count: 0 }, action) => {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
default:
return state;
}
});
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>
);
}
function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}
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 (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}






