123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- import {tabStore} from '@stores';
- import {useReducer} from 'react';
- import {createContext} from 'use-context-selector';
- type State = {
- key: string;
- url: string;
- label: string;
- }[];
- type Action =
- | {type: 'ADD'; payload: State[0]}
- | {type: 'REMOVE'; payload: string}
- | {type: 'CLEAR'};
- const defaultTab: State[0] = {key: '-1', url: '/main', label: '首页'};
- function reducer(state: State, action: Action): State {
- const {type} = action;
- const {key, dispatch} = tabStore.getState();
- switch (type) {
- case 'ADD': {
- const {payload} = action;
- dispatch(payload.key);
- const exist = state.find(val => val.key === payload.key);
- if (exist) {
- return state;
- }
- return [...state, payload];
- }
- case 'REMOVE': {
- const {payload} = action;
- const idx = state.findIndex(val => val.key === payload);
- if (idx < 0) return state;
- key === state[idx].key && dispatch(state[idx - 1].key);
- const nextState = [...state];
- nextState.splice(idx, 1);
- return nextState;
- }
- case 'CLEAR': {
- dispatch('-1');
- return [{...defaultTab}];
- }
- default:
- return state;
- }
- }
- export function useContextReudcer() {
- return useReducer(reducer, [defaultTab]);
- }
- export const context = createContext<ReturnType<typeof useContextReudcer>>([
- [],
- () => null,
- ]);
|