一、前期准备
二、文件目录
三、代码案例
./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