【发布时间】:2017-07-10 18:55:39
【问题描述】:
使用react-router 中的Match 和Miss 组件相对于Router 组件有什么优势?我似乎在react-router docs 中找不到任何关于此的文档。
我的问题源于查看react-universally 样板,更准确地说,通过查看此处:https://github.com/ctrlplusb/react-universally
【问题讨论】:
标签: reactjs react-router
使用react-router 中的Match 和Miss 组件相对于Router 组件有什么优势?我似乎在react-router docs 中找不到任何关于此的文档。
我的问题源于查看react-universally 样板,更准确地说,通过查看此处:https://github.com/ctrlplusb/react-universally
【问题讨论】:
标签: reactjs react-router
<Match> 和 <Miss> 是 React Router v4 的 alpha 版本中的组件。
在测试版中,<Match> 已重命名为 <Route>(其属性已更改,pattern 现在是 path,exactly 是 exact)。 <Miss> 组件被完全删除。相反,您应该使用<Switch> 语句,它只会呈现匹配的第一个<Route>(或<Redirect>)。您可以添加一个无路径组件作为<Switch> 的路由的最后一个子组件,当前面的<Route>s 都不匹配时,它将呈现。
您可以查看API documentation了解更多详情。
<Switch>
<Route exact path='/' component={Home} />
<Route path='/about' component={About} />
// The following <Route> has no path, so it will always
// match. This means that <NoMatch> will render when none
// of the other <Route>s match the current location.
<Route component={NoMatch} />
</Switch>
【讨论】:
要添加到最后一篇文章,您可以在react-router-dom 中找到它。它不再在 react-router 核心库中。
这是我发现的一种适用于反应路由的模式。基本上和以前的海报一样。您需要构建包含的其他组件。
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
{/* 在此处导入您的组件 */}
class Root extends React.Component{
render(){
return(
<Router>
<Switch>
<Route exact path='/' component={App} /> )} />
<Route path="/some-component" component={SomeComponent} />
<Route component={NotFound}/>
</Switch>
</Router>
);
}
}
render(<Root/>, document.querySelector('#main'));
【讨论】: