我将react路由器dom的location prop to setState设置为false,并且仅当react中的值为true时才渲染组件:
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}
因此,只要位置发生变化,useEffect就会运行,如果位置等于其中一个开关情况,它就会setState为false,并且FilterComp组件将被隐藏。
问题是/add/:id
路由位置路径名将如下所示:
/add/2
在switch语句中使用'/add/:id‘不起作用,所以我必须知道所有的:id,并在switch语句中包含它们,这是不可能的。
我找不到像其他路由一样在switch语句中包含此逻辑的方法。
当位置属性有像这样的/add/:something
参数时,我如何正确地setState到false?
发布于 2020-09-01 13:12:23
您可以使用if
而不是switch
。
if (location.pathname.startsWith('/add/')) {
setShowFilter(false)
} else if (location.pathname.startsWith('/signup')) {
setShowFilter(false)
} else {
setShowFilter(true)
}
发布于 2020-09-01 14:01:37
据我所知,您不能将正则表达式用作switch
语句;您可以使用一系列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]);
// ...
https://stackoverflow.com/questions/63688249
复制相似问题