1. store目录结构设计
2. react组件中使用store中的数据——useSelector
3. react组件中修改store中的数据——useDispatch
4. 示例
- react-basic\src\store\moduels\counterStore.js
import { createSlice } from '@reduxjs/toolkit'const counterStore = createSlice({name: 'counter',// 初始化stateinitialState: {count: 0,},// 修改状态的方法,支持直接修改reducers: {plus(state) {state.count++},minus(state) {state.count--}}
})const { plus, minus } = counterStore.actions
const reducer = counterStore.reducer// 按需导出
export { plus, minus }
// 默认导出
export default reducer
- react-basic\src\store\index.js
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from './moduels/counterStore'const store = configureStore({reducer: {counter: counterReducer}
})export default store
- react-basic\src\index.js
// 项目的入口文件,从这里开始运行// react必要的核心包
import React from 'react';
import ReactDOM from 'react-dom/client';
import store from './store/index'
import { Provider } from 'react-redux'
// 项目的根组件
import App from './App';// 把根组件渲染到id为root的dom节点上
// react-basic\public\index.html
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Provider store={store}><App /></Provider>
);
- react-basic\src\App.js
import { useSelector, useDispatch } from 'react-redux'
import { plus, minus } from './store/moduels/counterStore';function App() {const { count } = useSelector(state => state.counter)const dispatch = useDispatch()return (<div className="App"><button onClick={()=>dispatch(plus())}>+1</button>{count}<button onClick={()=>dispatch(minus())}>-1</button></div>);
}export default App;
5. 提交action传参
- react-basic\src\store\moduels\counterStore.js
import { createSlice } from '@reduxjs/toolkit'const counterStore = createSlice({name: 'counter',// 初始化stateinitialState: {count: 0,},// 修改状态的方法,支持直接修改reducers: {plus(state) {state.count++},minus(state) {state.count--},addToNum(state, actions) {state.count = actions.payload}}
})const { plus, minus, addToNum } = counterStore.actions
const reducer = counterStore.reducer// 按需导出
export { plus, minus, addToNum }
// 默认导出
export default reducer
- react-basic\src\App.js
import { useSelector, useDispatch } from 'react-redux'
import { plus, minus, addToNum } from './store/moduels/counterStore';function App() {const { count } = useSelector(state => state.counter)const dispatch = useDispatch()return (<div className="App"><button onClick={()=>dispatch(plus())}>+1</button>{count}<button onClick={()=>dispatch(minus())}>-1</button><button onClick={() => dispatch(addToNum(10))}>add to 10</button><button onClick={() => dispatch(addToNum(20))}>add to 20</button></div>);
}export default App;
6. 参考
黑马程序员react教程