【发布时间】:2022-12-13 22:07:12
【问题描述】:
到目前为止,我的代码运行良好:选项卡指示器正在相应地移动到我的选项卡的 url。 但是当浏览器的后退按钮被按下时,会发生一种奇怪的行为,url 正在改变,但指示器与以前一样停留在同一个选项卡上。
这是代码:
import * as React from 'react';
import { Tabs, Tab, Box } from '@mui/material';
import { useNavigate } from 'react-router-dom';
import { HOME_PAGE } from '../../../router/customRouter';
const navigationsListTabs = [
{
id: 0,
path: '/dev',
label: 'Dev',
isDisable: false,
},
{
id: 1,
path: '/images',
label: 'Images',
isDisable: false,
},
{
id: 2,
path: '/services',
label: 'Services',
isDisable: false,
},
{
id: 3,
path: '/users',
label: 'users',
isDisable: true,
},
];
export const Header = () => {
const [value, setValue] = React.useState(0);
const navigate = useNavigate();
React.useEffect(() => {
navigate('/dev');
}, []);
function handleChange(event, newValue) {
const selectedTab = navigationsListTabs.find((tab) => tab.id === newValue);
navigate(HOME_PAGE + selectedTab.path);
setValue(newValue);
}
return (
<Box sx={{ width: '100%' }}>
<Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
<Tabs
value={value}
onChange={handleChange}
data-testid="tabs-menu-component"
>
{navigationsListTabs.map((item) => (
<Tab
key={item.id}
value={item.id}
label={item.label}
aria-label={item.label}
disabled={item.isDisable}
/>
))}
</Tabs>
</Box>
</Box>
);
};
到目前为止尝试过: 使用多个条件比较 url(不工作):
let url = window.location.pathname;
console.log(url);
const valueGetter = () => {
if (url.includes('dev')) {
return 0;
} else if (url.includes('images')) {
return 1;
} else if (url.includes('services')) {
return 2;
} else {
return 3;
}
};
console.log(valueGetter());
const [value, setValue] = React.useState(valueGetter);
感谢任何能提供帮助的人 :)
【问题讨论】:
标签: javascript reactjs material-ui tabs