- 安装 redux 和 toolkit
npm i react-redux @reduxjs/toolkit
-
创建 store
在 src 目录下创建 store 文件夹,并在 store 文件夹下创建 index.js 文件 -
在 store 下创建对应业务的 js 文件,来保存对应数据的状态,比如 user.js、goods.js 等
代码演示:
import {
createSlice } from "@reduxjs/toolkit";
/** 创建一个user的切片 */
const userSlice = createSlice({
/** 切片的名称 */
name: "user-slice",
/** 切片的初始状态(也就是初始数据) */
initialState: {
name: "curry",
age: 18,
gender: "male",
},
/** 操作状态的方法 */
reducers: {
// 修改名称的方法
// 参数1:原始数据
// 参数2:action,action有两个属性:action.type和action.payload
// action.type:表示要执行的操作
// action.payload:表示要传递的数据
setName(state, action) {
state.name = action.payload;
},
setGender(state, action) {
state.gender = action.payload;
},
setAge(state, action) {
state.age = action.payload;
},
},
});
export default userSlice;
- 在 index.js 中将各个切片合并
代码演示:
import {
configureStore } from "@reduxjs/toolkit";
import userSlice from "./userSlice"