为什么活动选项卡重定向到React Material中的第一个选项卡

时间:2020-08-18 03:55:06

标签: reactjs material-ui react-material

我已经成功地根据路由重定向了选项卡。我的问题是,当我在第二个及随后的选项卡上时,当我刷新浏览器时,选项卡上的活动突出显示又回到了第一个选项卡上?

为什么会这样?请在下面检查我的代码

function TabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`scrollable-auto-tabpanel-${index}`}
      aria-labelledby={`scrollable-auto-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box pt={4}>
          <div>{children}</div>
        </Box>
      )}
    </div>
  );
}

TabPanel.propTypes = {
  children: PropTypes.node,
  index: PropTypes.any.isRequired,
  value: PropTypes.any.isRequired,
};

function a11yProps(index) {
  return {
    id: `scrollable-auto-tab-${index}`,
    'aria-controls': `scrollable-auto-tabpanel-${index}`,
  };
}

const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
    maxWidth: 640,
  },
}));

export default function Settings() {
  const classes = useStyles();
  const [value, setValue] = React.useState(0);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  return (
    <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>
  );

1 个答案:

答案 0 :(得分:0)

因此,您想在不同的路线上渲染相同的组件

 <BrowserRouter>
        <Route path={"/"} exact component={TabComponent} />
        <Route path={"/users"} exact component={TabComponent} />
        <Route path={"/products"} exact component={TabComponent} />
        <Route path={"/sales"} exact component={TabComponent} />
   </BrowserRouter>

并且要根据路由路径保持活动选项卡,可以通过在useEffect中检查路径名来实现。

  useEffect(() => {
    const pathname = props.history.location.pathname;
    switch (pathname) {
      default:
        setValue(0);
        break;
      case "/users":
        setValue(0);
        break;
      case "/products":
        setValue(1);
        break;
      case "/sales":
        setValue(2);
        break;
    }

  }, [props.history.location.pathname]);

这里是工作示例:https://codesandbox.io/s/floral-rgb-6o55s?fontsize=14&hidenavigation=1&theme=dark