问题描述
我对 React 比较陌生,我想知道这里的标准是什么.
I'm relatively new to React and I'm wondering what's the standard here.
想象一下我有一个这样的反应路由器:
Imagine I have a react-router like this one:
<Router history={history}>
<Route path="/" component={App}>
<Route path="home component={Home} />
<Route path="about" component={About} />
<Route path="inbox" component={Inbox} />
<Route path="contacts" component={Contacts} />
</Route>
</Router>
现在,如果 prop.mail
设置为 false
,我想删除两条路由,所以这样做的明智方法如下所示:
And now I want to remove two routes if prop.mail
is set to false
, so a sane way of doing that would look like this:
<Router history={history}>
<Route path="/" component={App}>
<Route path="home component={Home} />
<Route path="about" component={About} />
{ if.this.props.mail ?
<Route path="inbox" component={Inbox} />
<Route path="contacts" component={Contacts} />
: null }
</Route>
</Router>
但是有 2 条路由并且 React 返回错误:
But there are 2 routes and React returns error:
表达式必须有一个父元素.
我不想在这里使用多个 if.处理此问题的首选 React 方式是什么?
I don't want to use multiple ifs here. What's the preferred React way of handling this?
推荐答案
将它们放在一个数组中(也分配键):
Put them in an array (assign the keys also):
{ if.this.props.mail ?
[
<Route key={0} path="inbox" component={Inbox} />,
<Route key={1} path="contacts" component={Contacts} />
]
: null }
使用最新的 React 版本,您可以尝试 React.Fragment
也是这样:
With latest React version, you can try React.Fragment
also, like this:
{ if.this.props.mail ?
<React.Fragment>
<Route path="inbox" component={Inbox} />,
<Route path="contacts" component={Contacts} />
</React.Fragment>
: null }
这篇关于React - 表达式必须有一个父元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!