First, basic use

  • 1. Official website address

  • 2. Install directly in the project

    npm install @reduxjs/toolkit react-redux
    Copy the code
  • 3. Check the dependency packages of @reduxjs/ Toolkit

    The Thunk package for handling asynchrony is automatically integrated

    ."dependencies": {
        "immer": "^ 9.0.1"."redux": "^ 4.0.0"."redux-thunk": "^ 2.3.0." "."reselect": "^ 4.0.0"},...Copy the code
  • 4. Create an activity/slice.ts file in the Store folder

    import { createSlice, PayloadAction} from '@reduxjs/toolkit';
    
    export interface ActivityState {
      data: any;
      total: number;
      pageNumber: number;
      pageSize: number;
      loading: boolean; // Request data
      error: string | null; // Is there an error
    }
    
    const initialState: ActivityState = {
      data: [].total: 0.pageNumber: 1.pageSize: 10.loading: true.error: null,}export const activityListSlice = createSlice({
      name: 'activity', 
      initialState,
      reducers: {
        fetchStart: (state) = > {
          // return { ... state, loading: true };
          state.loading = true;
        },
        fetchSuccess: (state, action) = >{
          // return {
          / /... state,
          // loading: false,
          // data: action.payload.data,
          // total: action.payload.total,
          // pageNumber: action.payload.pageNumber,
          // pageSize: action.payload.pageNumber,
          // };
          state.loading = false;
          state.data = action.payload.data;
          state.total = action.payload.total;
          state.pageNumber = action.payload.pageNumber;
          state.pageSize = action.payload.pageSize;
        },
        fetchFail: (state, action: PayloadAction<string | null>) = > {
          state.loading = false; state.error = action.payload; }}})Copy the code
  • 5. Merge reducer in the import file of Store

    mport { combineReducers, configureStore } from '@reduxjs/toolkit';
    import { activityListSlice } from './activity/slice';
    
    Merge multiple reducers
    const rootReducer = combineReducers({
      ...
      activity: activityListSlice.reducer,
    })
    const store = configureStore({
      reducer: rootReducer,
      // You can add your own middleware, such as log printing
      middleware: (getDefaultMiddleware) = > [...getDefaultMiddleware()],
      devTools: true});// Get all store data types
    export type RootState = ReturnType<typeof store.getState>;
    
    export default store;
    Copy the code
  • 6. Call the remote API directly from the page component

    import React, { PropsWithChildren, useEffect } from 'react';
    import { RouteComponentProps } from 'react-router-dom';
    import {useDispatch} from 'react-redux';
    import { useSelector } from '.. /.. /redux/hooks';
    import { activityListSlice } from '.. /.. /redux/activity/slice';
    import axios from 'axios';
    
    interface MatchParams {
      id: string;
    }
    
    type Props = PropsWithChildren<RouteComponentProps<MatchParams>>;
    
    export const Detail: React.FC<Props> = (props: Props) = > {
      console.log(props);
      const loading = useSelector(state= >state.activity.loading);
      const activityList = useSelector(state= > state.activity.data);
      const dispatch = useDispatch();
    	// Load data as soon as the page comes in
      useEffect(() = > {
        const fetchData = async () => {
          dispatch(activityListSlice.actions.fetchStart());
          try {
            const { data } = await axios.get('https://xxxx/api/v1/front/activity');
            const {code, message, result} = data;
            if (Object.is(code, 0)) {
              dispatch(activityListSlice.actions.fetchSuccess(result));
            } else{ dispatch(activityListSlice.actions.fetchFail(message)); }}catch(e) { dispatch(activityListSlice.actions.fetchFail(e.messages)); } } fetchData(); } []);if (loading) {
        return <h1>Data loading</h1>
      }
      return (
        <div>
          {
            activityList.map(item => {
              return <li key={item.id}>{item.title}</li>})}</div>)}Copy the code

Second, put the request backend interface inreduxin

  • 1. Define the request method

    import { createSlice, PayloadAction, createAsyncThunk} from '@reduxjs/toolkit';
    import axios from 'axios';
    
    export const getActivityList = createAsyncThunk(
      'activity/getActivityList'./ / the only one
      async (params:any, thunkAPI) => {
        console.log(params, 'Parameters required by interface');
        thunkAPI.dispatch(activityListSlice.actions.fetchStart());
        try {
          const { data } = await axios.get('https://test.dancebox.cn/api/v1/front/activity');
          const { code, message, result } = data;
          if (Object.is(code, 0)) {
            thunkAPI.dispatch(activityListSlice.actions.fetchSuccess(result));
          } else{ thunkAPI.dispatch(activityListSlice.actions.fetchFail(message)); }}catch(e) { thunkAPI.dispatch(activityListSlice.actions.fetchFail(e.messages)); }});Copy the code
  • 2. Call a method on the page

    useEffect(() = > {
        dispatch(getActivityList({name: 'ha ha'.age:20})); } []);Copy the code

Another officially recommended way to request an interface

  • 1. Defined in redux

    export const getActivityList = createAsyncThunk(
      'activity/getActivityList'.async (params:any) = > {console.log(params, 'Parameters required by interface');
        const { data } = await axios.get('https://test.dancebox.cn/api/v1/front/activity');
        returndata; });export const activityListSlice = createSlice({
      name: 'activity', 
      initialState,
      reducers: {},// Note that this location is in extraReducers
      extraReducers: {
        [getActivityList.pending.type]: (state) = > {
          state.loading = true;
        },
        [getActivityList.fulfilled.type]: (state, action) = > {
          const { code, message, result: {data, total, pageSize, pageNumber} } = action.payload;
          if (Object.is(code, 0)) {
            state.loading = false;
            state.data = data;
            state.total = total;
            state.pageNumber = pageNumber;
            state.pageSize = pageSize;
          } else {
            state.loading = false;
            state.error = message;
          }
        },
        [getActivityList.rejected.type]: (state, action: PayloadAction<string | null>) = > {
          state.loading = false; state.error = action.payload; }}})Copy the code
  • 2. Call in the page

    useEffect(() = > {
        dispatch(getActivityList({name: 'ha ha'.age:20})); } []);Copy the code