react(18.2.0)+react-redux(8.0.2)+typescript(4.7.4)之全局调用接口,存储数据

一、前期准备

在这里插入图片描述

二、文件目录

在这里插入图片描述

三、代码案例

./type/global.d.ts

export {};
/**
 * Define interface under window
 */
declare global {
  interface Window {
    __REDUX_DEVTOOLS_EXTENSION_COMPOSE__: Function;
  }
}

./store/index.tsx

import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import reducers from './reducer';

type ReducerTodo = ReturnType<typeof reducers>;
export type RootState = ReducerTodo;
const composeEnhancers = typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;

const enhancer = composeEnhancers(
  applyMiddleware(thunk),
);

const store = createStore(reducers, enhancer);
export default store;

./store/reducer/index.tsx

import { combineReducers } from 'redux';
import dataReducer from './dataReducer';
import apiReducer from './apiReducer';

/**
 * Combination reducer
 */
export default combineReducers({
  dataReducer,
  apiReducer,
});

./store/reducer/apiReducer.tsx

import { IState, IAction } from '../../types/interfaceType';
import * as ActionType from '../../constants/actionType';

/**
 * State and action of the initial session
 */
const initState: IState = {} as any;
const initAction: IAction = {
  type: ActionType,
  payload: {},
};
/**
 * About the reducer that requests the interface to store information
 * @param state
 * @param action
 * @returns
 */
const apiReducer = (state: IState = initState, action: IAction = initAction) => {
  switch (action.type) {
    case ActionType.API_SUCCESS:
      console.log('**success', action.payload);
      return { ...state, ...action.payload };
    case ActionType.API_FAIL:
      console.log('**fail', action.payload);
      return { ...state };
    default:
      return state;
  }
};
export default apiReducer;

./store/reducer/dataReducer.tsx

import { IState, IAction } from '../../types/interfaceType';
import * as ActionType from '../../constants/actionType';

/**
 * State and action of the initial session
 */
const initState: IState = {
  headerInfo: {
    titleIndex: 0,
    sideOpen: false,
    statusObj: '',
  },
};
const initAction: IAction = {
  type: ActionType,
  payload: {},
};
/**
 * About the reducer of data storage information
 * @param state
 * @param action
 * @returns
 */
const dataReducer = (state: IState = initState, action: IAction = initAction) => {
  switch (action.type) {
    case ActionType.INIT:
      return state;
    case ActionType.HEADER_INFO:
      console.log('state==', state, action.payload);
      return { ...state, ...action.payload };
    default:
      return state;
  }
};
export default dataReducer;

在redux中存放接口数据(轮询调用接口,当初始化页面调用接口时,清除轮询的接口的定时器,重新开启调用)
存放全局的Interface Type

在这里插入图片描述

./store/action/actionCreators.tsx

import * as ActionType from '../../constants/actionType';
import { globalStatus } from '../../api';
import { ApiRes } from '../../types/interfaceType';

/**
 * Data returned when the interface request is successful
 * @param key
 * @param response
 * @returns
 */
export const requestSuccess = (key: string, response: ApiRes) => {
  const obj = {
    type: ActionType.API_SUCCESS,
    payload: {} as any,
  };
  obj.payload[key as keyof typeof obj.payload] = response;
  console.log('obj', obj);
  return obj;
};

/**
 * Data returned when the interface request fails
 * @param response
 * @returns
 */
export const requestFail = (response: ApiRes) => ({
  type: ActionType.API_FAIL,
  payload: response,
});

/**
 * Globally invoked interface
 * @param dispatch
 */
export const getGlobalStatus = async (dispatch: any) => {
  const result = await globalStatus();
  console.log('result', result);
  const obj = {
    resultData: result.data || [],
    resultStatus: result.status,
  };
  await dispatch(requestSuccess('globalStatus', obj));
};

/**
 * Define global timers
 */
let timer: any = null;
/**
 * Poll the request global interface to obtain status data
 * @param dispatch
 * @returns
 */
export const getGlobalStatusReq = (dispatch: any) => (
  () => {
    try {
      getGlobalStatus(dispatch);
      if (timer) {
        clearInterval(timer);
      }
      timer = setInterval(() => {
        getGlobalStatus(dispatch);
      }, 10000);
    } catch (Error: any) {
      const obj = {
        errorMessage: Error.message || '',
      };
      console.log('Error', Error.message);
      dispatch(requestFail(obj));
    }
  }
)();

在页面中调用全局接口并获取数据

html

import { useDispatch, useSelector } from 'react-redux';
import { getGlobalStatusReq } from '../../store/action/actionCreators';

  const apiReducer = useSelector((state: RootState) => state.apiReducer);
  const dispatch = useDispatch();


  useEffect(() => {
    getGlobalStatusReq(dispatch);
    getWritebackList();
  }, []);// eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    // console.log('999999/', apiReducer.globalStatus);
  }, [apiReducer.globalStatus]);// eslint-disable-line react-hooks/exhaustive-deps
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值