[英]Using multiple conditions in ternary operator to stop rendering component on specific routs
I have a component - side menu.我有一个组件侧菜单。 I want to have it on all pages except singIn and singUp page.
我想在所有页面上都有它,除了 singIn 和 singUp 页面。 The way I choose to do it is to use "useLocation" and check location.pathname before rendering component.
我选择这样做的方式是使用“useLocation”并在渲染组件之前检查 location.pathname。 It looks something like that:
它看起来像这样:
let location = useLocation().pathname;
return (
location !== '/signin' && '/signup' ? (
<div>sidemenu</div>
) : (
<>
</>
)
But it works only with first statement.但它仅适用于第一个语句。 Is it possible to pass multiple statements?
是否可以传递多个语句? Or may be there is another method not to render component on two/three specific pages?
或者可能有另一种方法不在两个/三个特定页面上呈现组件?
Any boolean expression is valid in a ternary.任何 boolean 表达式在三进制中都有效。
However, location !== '/signin' && '/signup'
is parsed like:但是,
location !== '/signin' && '/signup'
被解析为:
(location !== '/signin') && ('/signup')
So you should instead write:所以你应该写:
`location !== '/signin' && location !== '/signup'
Also, instead of the syntax此外,而不是语法
(expression) ? (
<div>sidemenu</div>
) : (
<>
</>
)
if you don't want anything to be rendered in the false
case, you can just use:如果您不希望在
false
情况下呈现任何内容,则可以使用:
return (expression) && (<div>sidemenu</div>)
which will return false
and not render anything if the expression is false, or if the expression is true it will render your div.如果表达式为 false,它将返回
false
并且不呈现任何内容,或者如果表达式为 true,它将呈现您的 div。
Also, a nice syntax for checking lists of path names is to use includes
, like so:此外,检查路径名列表的一个很好的语法是使用
includes
,如下所示:
['/signin', '/signup'].includes(useLocation().pathname)
then you have a one-liner that is easily extensible if you decide you want to add another path如果您决定要添加另一条路径,那么您将拥有一个易于扩展的单线
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.