小编典典

React-表达式必须具有一个父元素?

reactjs

我是React的新手,我想知道这里的标准是什么。

想象一下,我有一个像这样的反应路由器:

<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,因此一种理智的做法如下所示:

<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>

但是有两条路线,React返回错误:

表达式必须具有一个父元素。

我不想在这里使用多个ifs。React首选的处理方式是什么?


阅读 2004

收藏
2020-07-22

共1个答案

小编典典

将它们放在一个数组中(也分配键):

{ if.this.props.mail ? 
    [
        <Route key={0} path="inbox" component={Inbox} />,
        <Route key={1} path="contacts" component={Contacts} />
    ]
: null }

使用最新的React版本,您也可以这样尝试
React.Fragment

{ if.this.props.mail ? 
    <React.Fragment>
        <Route path="inbox" component={Inbox} />,
        <Route path="contacts" component={Contacts} />
    </React.Fragment>
: null }
2020-07-22