在 React 中加载特定的选项卡组件
Load Specific Tab Component in React
我的 React 应用程序中有几个选项卡,我只想在单击它时加载该特定选项卡。
现在,我的问题是当我单击特定选项卡时其他选项卡也会呈现。我已经使用 console.log
来查看其他选项卡是否正在呈现并且确实是。我怎样才能防止这种情况发生。我只想在单击时加载标签。
请在这里查看我的codesandbox:
CLICK HERE
<div>
<AppBar position="static" color="inherit" className={classes.root}>
<Tabs
value={value}
onChange={handleChange}
indicatorColor="primary"
textColor="primary"
variant="scrollable"
scrollButtons="auto"
aria-label="scrollable auto tabs example"
>
<Tab label="Users" component={Link} to="/users" {...a11yProps(0)} />
<Tab
label="Products"
component={Link}
to="/products"
{...a11yProps(1)}
/>
<Tab label="Sales" component={Link} to="/sales" {...a11yProps(2)} />
</Tabs>
</AppBar>
<TabPanel value={value} index={0}>
<Users />
</TabPanel>
<TabPanel value={value} index={1}>
<Products />
</TabPanel>
<TabPanel value={value} index={2}>
<Sales />
</TabPanel>
</div>
您应该将从路径名中获取制表符值的任务分离到一个单独的实用程序函数中。因为当你在tab之间切换时,value被设置,触发handleChange
然后导致pathname改变,这也导致useEffect
中的函数(你用来从pathname获取tab值)也被触发也会导致意外行为
const getTabFromPathname = (pathname) => {
switch (pathname) {
case "/users":
return 0;
case "/products":
return 1;
case "/sales":
return 2;
default:
return 0;
}
};
function TabComponent(props) {
const classes = useStyles();
const [value, setValue] = React.useState(
getTabFromPathname(props.history.location.pathname)
);
const handleChange = (event, newValue) => {
setValue(newValue);
};
// ...
}
下面是用于修复的分叉代码和框
我的 React 应用程序中有几个选项卡,我只想在单击它时加载该特定选项卡。
现在,我的问题是当我单击特定选项卡时其他选项卡也会呈现。我已经使用 console.log
来查看其他选项卡是否正在呈现并且确实是。我怎样才能防止这种情况发生。我只想在单击时加载标签。
请在这里查看我的codesandbox: CLICK HERE
<div>
<AppBar position="static" color="inherit" className={classes.root}>
<Tabs
value={value}
onChange={handleChange}
indicatorColor="primary"
textColor="primary"
variant="scrollable"
scrollButtons="auto"
aria-label="scrollable auto tabs example"
>
<Tab label="Users" component={Link} to="/users" {...a11yProps(0)} />
<Tab
label="Products"
component={Link}
to="/products"
{...a11yProps(1)}
/>
<Tab label="Sales" component={Link} to="/sales" {...a11yProps(2)} />
</Tabs>
</AppBar>
<TabPanel value={value} index={0}>
<Users />
</TabPanel>
<TabPanel value={value} index={1}>
<Products />
</TabPanel>
<TabPanel value={value} index={2}>
<Sales />
</TabPanel>
</div>
您应该将从路径名中获取制表符值的任务分离到一个单独的实用程序函数中。因为当你在tab之间切换时,value被设置,触发handleChange
然后导致pathname改变,这也导致useEffect
中的函数(你用来从pathname获取tab值)也被触发也会导致意外行为
const getTabFromPathname = (pathname) => {
switch (pathname) {
case "/users":
return 0;
case "/products":
return 1;
case "/sales":
return 2;
default:
return 0;
}
};
function TabComponent(props) {
const classes = useStyles();
const [value, setValue] = React.useState(
getTabFromPathname(props.history.location.pathname)
);
const handleChange = (event, newValue) => {
setValue(newValue);
};
// ...
}
下面是用于修复的分叉代码和框