在React中加载特定的选项卡组件

问题描述

我的react应用程序中有几个选项卡,我只想在单击该特定选项卡时加载它。 现在,我的问题是,当我单击特定选项卡时,其他选项卡也正在呈现。我已经使用console.log来查看其他选项卡是否正在渲染,实际上是否正在渲染。我如何防止这种情况发生。我只想在单击时加载标签

请在此处查看我的代码和框: 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>

解决方法

您应该将获取路径值中的制表符值的任务分为一个单独的实用程序函数。因为当您在制表符之间进行切换时,值已设置,因此触发handleChange然后更改路径名,这也会导致useEffect中的功能(您用来从路径名获取制表符值)也被触发也会导致意外行为

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);
  };

  // ...
}

下面是用于修复的分支代码和框

Edit Tabs-Material-UI-React (forked)