简体   繁体   English

如何在路线更改时隐藏反应组件?

[英]How to hide react component on route changes?

I'm using react router dom's location prop to setState to false and render component only If it's true like this in react:我正在使用 react router dom 的 location prop 将 setState 设置为 false 并仅渲染组件如果它在 react 中是这样的:

const [ showFilter, setShowFilter ] = useState(false);
const location = useHistory().location;

useEffect(() => {
            switch (location.pathname) {
                case '/signup':
                    return setShowFilter(false);
                case '/add/:id':
                    console.log(location);
                    return setShowFilter(false);
                default:
                    return setShowFilter(true);
            }
        },
        [ location ]
    );

   <Route exact path="/signup" component={SignUp} />
   <Route exact path="/add/:id" component={AddPage} />
{showFilter ? <FilterComp class="mr-2" location={location} /> : null}

So whenever the location changes the useEffect will run and If location is equal to one of switch cases it will setState to false and FilterComp component will be hidden.因此,只要位置发生变化,useEffect 就会运行,如果位置等于其中一个开关情况,它将 setState 设置为 false,并且 FilterComp 组件将被隐藏。

The problem is the /add/:id route location pathname will be something like this:问题是/add/:id路由位置路径名将是这样的:

/add/2

and using '/add/:id' in switch statement doesn't work so I have to know all the:id's and include all of them in switch statement which is impossible.并且在 switch 语句中使用 '/add/:id' 不起作用,所以我必须知道所有的:id 并将它们全部包含在 switch 语句中,这是不可能的。

I cant find a way to include this logic in the switch statement like other routes.我找不到像其他路由一样将此逻辑包含在 switch 语句中的方法。

How can I properly setState to false when the location prop has parameters like this /add/:something ?当 location 道具具有这样的参数/add/:something时,我如何正确地将 setState 设置为 false ?

Instead of switch , you can use if .您可以使用if代替switch

if (location.pathname.startsWith('/add/')) {
    setShowFilter(false)
} else if (location.pathname.startsWith('/signup')) {
    setShowFilter(false)
} else {
    setShowFilter(true)
}

As far as I know, you cannot use a regular expression as case of a switch statement;据我所知,您不能将正则表达式用作switch语句的情况; you can either use a series of if...else if...else statements or do something like this:您可以使用一系列if...else if...else语句或执行以下操作:

// ...    
const re = /^(\/signup)|^(\/add\/\d+)/; // a regular expression containing the routes where you want to hide the filter

useEffect(() => {
    setShowFilter(!re.test(location.pathname));
}, [location, re]);
// ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM