React class 组件使用@redux/toolkit

1,406 阅读1分钟

公司React项目由于时间久远,换了几波人,状态管理redux、dva都在用,hooks和class也同时存在。考虑到兼容性和可持续维护,项目准备升级到最新的React框架,由于dva一直没有更新和redux模版写法比较繁琐,准备使用@redux/toolkit,一来这个比较新,二来写法比较类似dva,代码量比较小,不用写很多模版代码,问题是很少关于class和@redux/toolkit的组合使用。

细节和api就不讲解了,感兴趣的直接参考官网,这里直接说流程,当笔记

1、orderSlice.ts 调用createSlice 创建myOrderSlice, 并初始化initialState, 调用同步和异步事件:

import {createSlice} from "@reduxjs/toolkit";
import { AppThunk } from "./store";


const myOrderSlice = createSlice({
    name: 'myneworder',
    initialState: {
       value: 0,
    },
    reducers: {
        increment: state => {
            state.value += 1;
          },
          decrement: state => {
            state.value -= 1;
          },
          incrementByAmount: (state, action) => {
            state.value += action.payload;
          },
    }
});

export const  incrementAsync =   (params: any): AppThunk => async dispatch => {
    const result = await fetch('https://api.github.com/users/ruanyf', {
      method: "get",
    }).then((response: Response) => response.json())

    console.log(result)   
  };

const { actions, reducer } = myOrderSlice;

export const { increment, decrement, incrementByAmount } = myOrderSlice.actions;

export default reducer;

2、store.ts 调用orderSlice

import { configureStore, ThunkAction, Action, combineReducers, createStore } from '@reduxjs/toolkit';
import myOrderSlice from "./orderSlice";

const rootReducer = combineReducers({
  newOrder2: myOrderSlice,
});

export type RootState = ReturnType<typeof rootReducer>;

const store = configureStore({
  reducer: rootReducer,
});

export default store;

// typescript type for the combined state
export type State = ReturnType<typeof rootReducer>;

export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  Action<string>
>;

3、页面调用:

import React from "react";
import { connect } from "react-redux";
import { increment, decrement, incrementAsync } from "../../reduxStore/orderSlice";
import { State } from "../../reduxStore/store";

interface MyComponentProps {
    increment: () => void;
    decrement: () => void;
    incrementAsync: any;
    count: number;
}

class MyComponent extends React.Component<MyComponentProps> {
    constructor(props: any) {
        super(props);
    }

    componentDidMount() {
        this.props.incrementAsync({ pageNum: 1, pageSize: 10 })
    }

    render() {
        return (
            <div>
                <h1>Count is {this.props.count}</h1>
                <button onClick={() => this.props.increment()}>
                    Increment
                </button>
                <button onClick={() => this.props.decrement()}>
                    Decrement
                </button>
            </div>
        );
    }
}

const mapStateToProps = (state: State) => ({
    count: state.newOrder2.value,
});

export default connect(mapStateToProps, { increment, decrement, incrementAsync })(MyComponent);

效果:

aaa.png

git:

github.com/kevinkekbx/…