1.配置环境
1.1开启项目
npx create-react-app react-redux-pro
1.2安装配套工具
说明:安装Redux Toolkit和react-redux。Redux Toolkit(RTK)~官方推荐编写Redux逻辑的方式,是一套工具的集合集,简化书写方式;react-redux-用来链接Redux和React组件的中间件。
npm i @reduxjs/toolkit react-redux
1.3启动
npm run start
2.创建文件夹
说明:在src下面安装store文件夹依次。
2.1counterStore.js
import {createSlice} from "@reduxjs/toolkit"const counterStore=createSlice({name:"counter",// 初始化状态initialState:{count:0},// 修改状态的方法 同步方法reducers:{inscrement(state){state.count++},decrement(state){state.count--}}
})// 解构actionCreater函数
const {inscrement,decrement}= counterStore.actions
// 获取reducer
const reducer=counterStore.reducer// 按需导出actionCreator
export {inscrement,decrement}// 以默认导出的方式导出reducer
export default reducer
2.2index.js
import { configureStore} from "@reduxjs/toolkit"
// 导入子模块reducer
import counterReducer from "./modules/counterStore"const store=configureStore({reducer:{counter:counterReducer}
})export default store
2.3app.js
import { useDispatch, useSelector } from "react-redux";
import {inscrement,decrement} from "./store/modules/counterStore"
function App() {const {count}=useSelector(state=>state.counter)const dispatch=useDispatch()return (<div className="App">{count}<button onClick={()=>dispatch(inscrement())}>+</button><button onClick={()=>dispatch(decrement())}>-</button></div>);
}export default App;