使用redux-toolkit简化react中redux的操作

一、基本使用

  • 1、官网地址

  • 2、在项目中直接安装

    npm install @reduxjs/toolkit react-redux
    
  • 3、查看@reduxjs/toolkit的依赖包

    其中自动集成了thunk处理异步的包

    ...
    "dependencies": {
        "immer": "^9.0.1",
        "redux": "^4.0.0",
        "redux-thunk": "^2.3.0",
        "reselect": "^4.0.0"
      },
    ...
    
  • 4、在store文件夹下创建一个activity/slice.ts文件

    import { createSlice, PayloadAction} from '@reduxjs/toolkit';
    
    export interface ActivityState {
      data: any;
      total: number;
      pageNumber: number;
      pageSize: number;
      loading: boolean; // 请求数据中
      error: string | null; // 是否错误
    }
    
    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;
        }
      }
    })
    
  • 5、在store的入口文件中合并reducer

    mport { combineReducers, configureStore } from '@reduxjs/toolkit';
    import { activityListSlice } from './activity/slice';
    
    // 合并多个reducer
    const rootReducer = combineReducers({
      ...
      activity: activityListSlice.reducer,
    })
    const store = configureStore({
      reducer: rootReducer,
      // 可以添加自己的中间件,比如打印日志的
      middleware: (getDefaultMiddleware) => [...getDefaultMiddleware()],
      devTools: true,
    });
    
    // 获取全部store数据类型
    export type RootState = ReturnType<typeof store.getState>;
    
    export default store;
    
  • 6、在页面组件中直接调用远程api接口

    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();
    	// 页面一进来就加载数据
      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>数据加载中</h1>
      }
      return (
        <div>
          {
            activityList.map(item => {
              return <li key={item.id}>{item.title}</li>
            })
          }
        </div>
      )
    }
    

二、将请求后端接口也放到redux中去

  • 1、定义请求方法

    import { createSlice, PayloadAction, createAsyncThunk} from '@reduxjs/toolkit';
    import axios from 'axios';
    
    export const getActivityList = createAsyncThunk(
      'activity/getActivityList', // 唯一的
      async (params:any, thunkAPI) => {
        console.log(params, '接口需要的参数');
        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));
        }
      }
    );
    
  • 2、在页面中调用方法

    useEffect(() => {
        dispatch(getActivityList({name: '哈哈', age:20}));
    }, []);
    

三、另外一种官方推荐的请求接口的方式

  • 1、在redux中定义

    export const getActivityList = createAsyncThunk(
      'activity/getActivityList',
      async (params:any) => {
        console.log(params, '接口需要的参数');
        const { data } = await axios.get('https://test.dancebox.cn/api/v1/front/activity');
        return data;
      }
    );
    
    export const activityListSlice = createSlice({
      name: 'activity', 
      initialState,
      reducers: {
        
      },
      // 注意这个位置是在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;
        }
      }
    })
    
  • 2、在页面中调用

    useEffect(() => {
        dispatch(getActivityList({name: '哈哈', age:20}));
    }, []);
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水痕01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值