reduxjs/toolkit使用

reduxjs/toolkit使用

1、安装

要和react-redux一起使用

cnpm i react-redux @reduxjs/toolkit -D

2、新建redux文件夹

在下面新建store.ts、slice.ts、hook.ts三个文件

store.ts
import { configureStore } from "@reduxjs/toolkit";
import stateSlice from "./slice";
import otherSlice from "./otherSlice";

export const store = configureStore({
  // 每个reducer代表一个模块的状态管理器
  reducer: {
    state: stateSlice,
    other: otherSlice,
  },
});

// RootState作用是返回store的方法getState的类型 function
export type RootState = ReturnType<typeof store.getState>;

// AppDispatch 作用是拿到Store的dispatch方法的类型 function
export type AppDispatch = typeof store.dispatch;

slice.ts
import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
interface InitialState {
  count: number;
  text?: string;
}

const initialState: InitialState = {
  count: 0,
  text: "我是文字",
};

interface PromiseNum {
  number: number;
}

const promise_one: Promise<PromiseNum> = new Promise((res, rej) => {
  setTimeout(() => {
    res({ number: 10 });
  }, 3000);
});

// 异步Action
export const getAsyncInfo = createAsyncThunk("getAsyncInfo", async () => {
  const data = await promise_one;
  return data;
});

export const stateSlice = createSlice({
  name: "state",
  initialState,
  reducers: {
    add: (state) => {
      state.count += 1;
    },
    minus: (state) => {
      state.count -= 1;
    },
    change: (state) => {
      state.text = "我是改变了的文字";
    },
    back: (state) => {
      state.text = "我是文字";
    },
  },
  extraReducers: (builder) => {
    // 进行请求阶段的一些操作
    builder.addCase(getAsyncInfo.pending, () => {
      console.log("进行中");
    });
    builder.addCase(getAsyncInfo.fulfilled, (state, action) => {
      console.log("action.payload: ", action.payload); //{number:"10"}
      console.log("state: ", state.text); //我是文字
      state.count += action.payload.number;
      console.log("成功");
    });
    builder.addCase(getAsyncInfo.rejected, () => {
      console.log("失败");
    });
  },
});

export const { add, minus, change, back } = stateSlice.actions;
export default stateSlice.reducer;




hook.ts
import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
import type { RootState, AppDispatch } from "./store";

// use hook 节约每次引入type的工作
// useSelector: 节约配置RootState type

export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

4、使用

首先是在根页面,引入store,Provider

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

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <Provider store={store}>
    <App />
    </Provider>
  </React.StrictMode>
);


reportWebVitals();

然后在对应页面中使用:

import React from "react";
import { shallowEqual } from "react-redux";
import { useAppDispatch, useAppSelector } from "../redux/hook";
import { add, minus, getAsyncInfo } from "../redux/slice";

export const APage = () => {
  console.log("A渲染了");

  const { count } = useAppSelector((state: any) => ({ ...state.state }), shallowEqual);
  const dispatch = useAppDispatch();

  return (
    <div>
      <h1>我是Apage</h1>
      <h2>我是count:{count}</h2>
      <button
        onClick={() => {
          dispatch(add());
        }}
      >1
      </button>
      <button
        onClick={() => {
          dispatch(minus());
        }}
      >1
      </button>
      <button
        onClick={() => {
          dispatch(getAsyncInfo());
        }}
      >
        异步加10
      </button>
    </div>
  );
};

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值