react antd 退出登录清空所有页签
时间: 2023-07-25 15:26:16 浏览: 58
可以通过以下步骤实现:
1. 在退出登录的处理函数中,调用 `window.localStorage.clear()` 清空本地存储。
2. 在 `App` 组件中使用 `React` 的 `useState` 钩子来维护当前打开的页签列表,以及当前激活的页签。
3. 在 `App` 组件的 `useEffect` 钩子中监听 `localStorage` 的变化,如果发现 `localStorage` 被清空了,则清空当前打开的页签列表,并将当前激活的页签设置为 `null`。
4. 在 `Tabs` 组件中,使用 `React` 的 `useEffect` 钩子来监听当前激活的页签是否为 `null`,如果是,则重定向到登录页。
下面是示例代码:
```jsx
import React, { useState, useEffect } from 'react';
import { Tabs } from 'antd';
const { TabPane } = Tabs;
const App = () => {
const [activeKey, setActiveKey] = useState(null);
const [panes, setPanes] = useState([]);
const handleLogout = () => {
window.localStorage.clear();
};
useEffect(() => {
const panesFromStorage = window.localStorage.getItem('panes');
if (panesFromStorage) setPanes(JSON.parse(panesFromStorage));
const activeKeyFromStorage = window.localStorage.getItem('activeKey');
if (activeKeyFromStorage) setActiveKey(activeKeyFromStorage);
}, []);
useEffect(() => {
window.localStorage.setItem('panes', JSON.stringify(panes));
window.localStorage.setItem('activeKey', activeKey || '');
}, [panes, activeKey]);
useEffect(() => {
const handleStorageChange = () => {
if (!window.localStorage.getItem('panes')) {
setPanes([]);
setActiveKey(null);
}
};
window.addEventListener('storage', handleStorageChange);
return () => {
window.removeEventListener('storage', handleStorageChange);
};
}, []);
const handleTabChange = (key) => {
setActiveKey(key);
};
const handleEdit = (targetKey, action) => {
if (action === 'remove') {
const nextPanes = panes.filter((pane) => pane.key !== targetKey);
setPanes(nextPanes);
if (activeKey === targetKey) {
setActiveKey(nextPanes[nextPanes.length - 1].key);
}
}
};
return (
<>
<button onClick={handleLogout}>退出登录</button>
<Tabs
activeKey={activeKey}
onChange={handleTabChange}
type="editable-card"
onEdit={handleEdit}
>
{panes.map((pane) => (
<TabPane tab={pane.title} key={pane.key}>
{pane.content}
</TabPane>
))}
</Tabs>
</>
);
};
export default App;
```
在上面的代码中,我们使用 `useState` 钩子来维护当前打开的页签列表 `panes`,以及当前激活的页签 `activeKey`。在 `handleLogout` 函数中,我们调用 `window.localStorage.clear()` 清空本地存储。在 `useEffect` 钩子中,我们从本地存储中读取 `panes` 和 `activeKey`,并将它们保存到组件的状态中。在 `useEffect` 钩子中,我们还监听 `localStorage` 的变化,如果发现 `localStorage` 被清空了,则清空当前打开的页签列表,并将当前激活的页签设置为 `null`。在 `Tabs` 组件中,我们使用 `useEffect` 钩子来监听当前激活的页签是否为 `null`,如果是,则重定向到登录页。