当前位置:   article > 正文

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

react18.2.0 createstore

一、前期准备

在这里插入图片描述

二、文件目录

在这里插入图片描述

三、代码案例

./type/global.d.ts

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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

./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;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

./store/reducer/index.tsx

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

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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

./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;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

./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;

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
在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));
    }
  }
)();

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
在页面中调用全局接口并获取数据

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/510785
推荐阅读
相关标签
  

闽ICP备14008679号