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>([ [], () => null, ]);