React如何创建store
创建 Redux Store 的基本步骤
安装 Redux 和 React-Redux 依赖包:
npm install redux react-redux
创建 reducer 函数管理状态:
const initialState = {
count: 0
};
function rootReducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
case 'DECREMENT':
return { ...state, count: state.count - 1 };
default:
return state;
}
}
使用 createStore 创建 store 实例:
import { createStore } from 'redux';
const store = createStore(rootReducer);
在 React 应用中集成 Store
使用 Provider 包裹根组件:
import { Provider } from 'react-redux';
import ReactDOM from 'react-dom';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
在组件中访问 Store
使用 useSelector 读取状态:
import { useSelector } from 'react-redux';
function Counter() {
const count = useSelector(state => state.count);
return <div>{count}</div>;
}
使用 useDispatch 派发 action:
import { useDispatch } from 'react-redux';
function Buttons() {
const dispatch = useDispatch();
return (
<>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
</>
);
}
配置中间件
安装 redux-thunk 处理异步操作:
npm install redux-thunk
应用中间件创建 store:
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(rootReducer, applyMiddleware(thunk));
模块化 Reducers
使用 combineReducers 合并多个 reducer:
import { combineReducers } from 'redux';
const rootReducer = combineReducers({
counter: counterReducer,
user: userReducer
});





