【问题标题】:Hide Element in React Based on Routing基于路由的 React 中隐藏元素
【发布时间】:2021-03-10 23:58:54
【问题描述】:

如果路由是/jobs/account,我想隐藏RightMenu。 我的问题是,如果/jobs/account 有像/jobs/1/accounts/2 这样的子路由。我将如何包括它?有没有办法隐藏这个?有没有比我的代码更好的方法?

更新

如果我们想在/jobs/new 上显示RightMenu 而不是在/jobs/1 上显示呢?类似的东西。

请在此处查看我的代码框CLICK HERE

const noRightMenusRoutes = ["/jobs", "/account"];

  const noRightMenus = () => {
    return (
      noRightMenusRoutes.findIndex((el) => el.includes(location.pathname)) !==
      -1
    );
  };

【问题讨论】:

    标签: reactjs ecmascript-6 react-router react-hooks react-router-dom


    【解决方案1】:

    最好的方法是使用当路径名改变时会更新的状态:

    import React, { Suspense, lazy, useState, useEffect } from "react";
    ....
    
    function PagesRoute({ match: { url } }) {
      const classes = useStyles();
      const location = useLocation();
      const [showMenu, setShowMenu] = useState(true);
      const [noRightMenusRoutes, setNoRightMenusRoutes] = useState([
        "/jobs",
        "/account"
      ]);
    
      useEffect(() => {
        console.log(location.pathname);
        const noRightMenus = noRightMenusRoutes.findIndex((el) => {
          return location.pathname.includes(el);
        });
    
        setShowMenu(noRightMenus === -1);
      }, [location, noRightMenusRoutes]);
    
      ...
    
     <Grid item xl={3} lg={3} md={3}>
                    {!showMenu ? null : <RightMenu />}
     </Grid>
    

    您不应该在 JSX 中使用函数来进行渲染,这些函数可以用作事件处理程序。

    【讨论】:

    • 谢谢。如果我们想在/jobs/new 上显示RightMenu 而不是在/jobs/1 上显示呢?类似的东西....你可以将两个独立的功能集成到一个中,这样如果我们有很多路线会更容易吗?谢谢
    【解决方案2】:

    React 路由器的 matchPath 函数是处理这些事情的非常方便的实用程序 你可以这样做

    const noRightMenusRoutes = ["/jobs", "/account"];
    const isMatching = noRightMenusRoutes.some(path => {
        const match = matchPath(location.pathname, {
          path: path,
          exact: true
        })
        return match && match.isExact
    })
    

    使用它还可以帮助您处理带有 /jobs/:jobId 等参数的路径

    【讨论】:

      猜你喜欢
      • 2016-09-16
      • 2017-05-21
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      • 2020-03-15
      • 1970-01-01
      • 2011-06-23
      • 1970-01-01
      相关资源
      最近更新 更多