React - expressions must have one parent element?

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

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> 

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> 

But there are 2 routes and React returns error:

expressions must have one parent element.

I don't want to use multiple ifs here. What's the preferred React way of handling this?

回答1:

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 } 

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 } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!