二十、@reduxjs/toolkit

郁子大约 3 分钟约 840 字笔记React18ReduxRTK李立超

(一) 使用 RTK 创建 store

1. src/index.js

import ReactDOM from "react-dom/client";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(<App />);

2. src/App.jsx

import React from "react";
import "./store";

const App = () => {
  return <div>App</div>;
};

export default App;

3. src/store/index.js

yarn add react-redux @reduxjs/toolkit

1)createSlice 创建 reducer 的切片,参数是配置对象

  • name 自动生成 action 中的 type
  • initialState 当前切片的 state 的初始值
  • reducers 指定 state 的各种操作方法,不同方法对应对 state 的不同操作

2)stuSlice.actions 切片对象会自动生成 action

  • actions 中存储的是 slice 自动生成的 action 创建器(函数),调用函数后会自动创建 action 对象
  • action 对象结构: { type: 切片name/函数名, payload: 调用函数的参数 }

3)configureStore 用来创建 store 对象,参数是配置对象

import { createSlice, configureStore } from "@reduxjs/toolkit";

const stuSlice = createSlice({
  name: "stu",
  initialState: {
    name: "孙悟空",
    age: 18,
    gender: "男",
    address: "花果山",
  },
  reducers: {
    // state 是state的代理对象,可以直接修改,无需浅复制原对象
    setName(state, action) {
      state.name = "猪八戒";
    },
    setAge(state, action) {
      state.age = 28;
    },
  },
});

export const { setName, setAge } = stuSlice.actions;
// // const nameAction = setName();
// const nameAction = setName("哈哈");
// console.log(nameAction);

// 创建store
const store = configureStore({
  reducer: {
    student: stuSlice.reducer,
  },
});

export default store;

(二) 完成 RTK 代码

1. src/index.js

import ReactDOM from "react-dom/client";
import App from "./App";
import { Provider } from "react-redux";
import store from "./store";

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
  <Provider store={store}>
    <App />
  </Provider>,
);

2. src/App.jsx

import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { setName, setAge } from "./store";

const App = () => {
  // 加载state中的数据
  const student = useSelector((state) => state.student);
  // 获取派发器对象
  const dispatch = useDispatch();

  const setNameHandler = () => {
    dispatch(setName("沙和尚"));
  };
  const setAgeHandler = () => {
    dispatch(setAge(30));
  };

  return (
    <div>
      <p>
        {student.name}---{student.age}---{student.gender}---{student.address}
      </p>
      <button onClick={setNameHandler}>修改name</button>
      <button onClick={setAgeHandler}>修改age</button>
    </div>
  );
};

export default App;

3. src/store/index.js

import { createSlice, configureStore } from "@reduxjs/toolkit";

const stuSlice = createSlice({
  name: "stu",
  initialState: {
    name: "孙悟空",
    age: 18,
    gender: "男",
    address: "花果山",
  },
  reducers: {
    // state 是state的代理对象,可以直接修改,无需浅复制原对象
    setName(state, action) {
      state.name = action.payload || "猪八戒";
    },
    setAge(state, action) {
      state.age = action.payload || 28;
    },
  },
});

export const { setName, setAge } = stuSlice.actions;

// 创建store
const store = configureStore({
  reducer: {
    student: stuSlice.reducer,
  },
});

export default store;

(三) 拆分 RTK 代码

1. src/App.jsx

import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { setName as setStudentName, setAge as setStudentAge } from "./store/studentSlice";
import { setName as setSchoolName, setAddress as setSchoolAddress } from "./store/schoolSlice";

const App = () => {
  // 加载state中的数据
  // const student = useSelector((state) => state.student);
  // const school = useSelector((state) => state.school);
  const { student, school } = useSelector((state) => state);

  // 获取派发器对象
  const dispatch = useDispatch();

  const setStudentNameHandler = () => {
    dispatch(setStudentName("沙和尚"));
  };
  const setAgeHandler = () => {
    dispatch(setStudentAge(30));
  };
  const setSchoolNameHandler = () => {
    dispatch(setSchoolName("高老庄中小"));
  };
  const setSchoolAddressHandler = () => {
    dispatch(setSchoolAddress("高老庄府前街19号"));
  };

  return (
    <div>
      <p>
        {student.name}---{student.age}---{student.gender}---{student.address}
      </p>
      <button onClick={setStudentNameHandler}>修改学生姓名</button>
      <button onClick={setAgeHandler}>修改学生年龄</button>
      <hr />
      <p>
        {school.name}---{school.address}
      </p>
      <button onClick={setSchoolNameHandler}>修改学校名称</button>
      <button onClick={setSchoolAddressHandler}>修改学校地址</button>
    </div>
  );
};

export default App;

2. src/store/index.js

import { configureStore } from "@reduxjs/toolkit";
import { studentReducer } from "./studentSlice";
import { schoolReducer } from "./schoolSlice";

// 创建store
const store = configureStore({
  reducer: {
    student: studentReducer,
    school: schoolReducer,
  },
});

export default store;

3. src/store/schoolSlice.js

import { createSlice } from "@reduxjs/toolkit";

// 学校信息
const schoolSlice = createSlice({
  name: "school",
  initialState: {
    name: "花果山一小",
    address: "花果山大街28号",
  },
  reducers: {
    setName(state, action) {
      state.name = action.payload;
    },
    setAddress(state, action) {
      state.address = action.payload;
    },
  },
});
export const { setName, setAddress } = schoolSlice.actions;
export const { reducer: schoolReducer } = schoolSlice;

4. src/store/studentSlice.js

import { createSlice } from "@reduxjs/toolkit";

// 学生信息
const studentSlice = createSlice({
  name: "stu",
  initialState: {
    name: "孙悟空",
    age: 18,
    gender: "男",
    address: "花果山",
  },
  reducers: {
    // state 是state的代理对象,可以直接修改,无需浅复制原对象
    setName(state, action) {
      state.name = action.payload || "猪八戒";
    },
    setAge(state, action) {
      state.age = action.payload || 28;
    },
  },
});
export const { setName, setAge } = studentSlice.actions;
export const { reducer: studentReducer } = studentSlice;
上次编辑于: