redux toolkit的学习

157 阅读2分钟

之前使用过react-redux,很麻烦. toolkit简化了很多代码

认识 redux toolkit

image.png

安装:

npm install @reduxjs/toolkit react-redux

1.创建分片 生成子reducer(同步)

// 创建切片 来生成reducer
import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";


const homeSlice = createSlice({
  name: "home", // 切片名字 保证唯一  这个会作为action type的前缀
  initialState: {
    // state默认值(初始化)
    counter: 123,
    homeData: [],
  },
  reducers: {
    // 同步action
    add(state, action) {
      const { payload } = action;
      state.counter += payload;
    },
    jian(state, action) {
      const { payload } = action;
      state.counter += payload;
    },
  },
});

// 是同步的action 其type为: home/add
export const { add, jian } = homeSlice.actions;
// 导出reducer
export default homeSlice.reducer;

2.合并reducer

// 创建store对象,合并 子reducer
import { configureStore } from "@reduxjs/toolkit";

import homeReducer from "./modules/home";
const store = configureStore({
  reducer: {
    home: homeReducer,
  },
  devTools: true,
});
export default store;

3.消费到app上

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

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

4.在页面中使用

import React, { useEffect } from "react";

import { useSelector, useDispatch } from "react-redux";

import { add, jian } from "../../store/modules/home";

export default function Index() {
  const { counter, homeData } = useSelector((state) => {
    console.log("state==>", state); // root的state
    return state.home; // home的state
  });
  const dispatch = useDispatch();
  return (
    <>
      <div>{counter}</div>
      <button
        onClick={() => {
          // 派发actio, 是在redux reducer中自动生成的
          dispatch(add(1));
        }}
      >
        +1
      </button>
      <button
        onClick={() => {
          dispatch(jian(1));
        }}
      >
        -1
      </button>
    </>
  );
}

5.异步action

5.1 使用createAsyncThunk

// 创建切片 来生成reducer
import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

// 异步action
import { createAsyncThunk } from "@reduxjs/toolkit";

export const getAsyncHomeData = createAsyncThunk(
  "home/homeData", // action type的前缀
  async (dispatch) => {
    console.log("dispatch==>", dispatch);
    const url = "http://codercba.com:9060/beike/api/powerscreen";
    const res = await axios.get(url);
    console.log("res==>", res);
    return res.data.data.chargingPile.data;
  }
);

const homeSlice = createSlice({
  name: "home", // 切片名字 保证唯一  这个会作为action type的前缀
  initialState: {
    // state默认值(初始化)
    counter: 123,
    homeData: [],
  },
  reducers: {
    // 同步action
    add(state, action) {
      const { payload } = action;
      state.counter += payload;
    },
    jian(state, action) {
      const { payload } = action;
      state.counter += payload;
    },
  },
  extraReducers(builder) {
    builder.addCase(getAsyncHomeData.fulfilled, (state, action) => {
      console.log("action.payload==>", action.payload); // action.payload就是接口返回的数据
      state.homeData = action.payload;
    });
  },
});

// 是同步的action 其type为: home/add
export const { add, jian } = homeSlice.actions;
// 导出reducer
export default homeSlice.reducer;

5.2 使用dispatch

import React, { useEffect } from "react";

// eslint-disable-next-line no-unused-vars
import { useSelector, useDispatch } from "react-redux";

// eslint-disable-next-line no-unused-vars
import { add, jian, getAsyncHomeData } from "../../store/modules/home";

export default function Index() {
  const { counter, homeData } = useSelector((state) => {
    console.log("state==>", state); // root的state
    return state.home; // home的state
  });
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(getAsyncHomeData(10000));
  }, []);
  return (
    <>
      <div>{counter}</div>
      <button
        onClick={() => {
          // 派发actio, 是在redux reducer中自动生成的
          dispatch(add(1));
        }}
      >
        +1
      </button>
      <button
        onClick={() => {
          dispatch(jian(1));
        }}
      >
        -1
      </button>
      <button
        onClick={() => {
          dispatch(getAsyncHomeData(10000));
        }}
      >
        gethomeData
      </button>

      {/* <div>{JSON.stringify(homeData)}</div> */}
      <div>
        {homeData.map((item) => {
          return (
            <div
              key={item.name}
              style={{
                color: item.color,
              }}
            >
              {item.name}
            </div>
          );
        })}
      </div>
    </>
  );
}

6.目录截图

image.png