您好,欢迎访问一九零五行业门户网

react router 4.0以上的路由如何应用

本文主要和大家介绍react router 4.0以上的路由应用详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧,希望能帮助到大家。
在4.0以下的react router中,嵌套的路由可以放在一个router标签中,形式如下,嵌套的路由也直接放在一起。
<route component={app}> <route path="groups" components={groups} /> <route path="users" components={users}> <route path="users/:userid" component={profile} /> </route> </route>
但是在4.0以后,嵌套的路由与之前的就完全不同了,需要单独放置在嵌套的根component中去处理路由,否则会一直有warning:
you should not use <route component> and <route children> in the same route
正确形式如下
<route component={app}> <route path="groups" components={groups} /> <route path="users" components={users}> //<route path="users/:userid" component={profile} /> </route> </route>
上面将嵌套的路由注释掉
const users = ({ match }) => ( <p> <h2>topics</h2> <route path={`${match.url}/:userid`} component={profile}/> </p> )
上面在需要嵌套路由的component中添加新的路由
一个完整的嵌套路由的例子如下
说明及注意事项
1.以下代码采用es6格式
2.react-router-dom版本为4.1.1
3.请注意使用诸如hashrouter之类的history,否则一直会有warning,不能渲染
import react, { component } from 'react'; import reactdom from 'react-dom'; // import { router, route, link, switch } from 'react-router'; import { hashrouter, route, link, switch } from 'react-router-dom'; class app extends component { render() { return ( <p> <h1>app</h1> <ul> <li><link to="/">home</link></li> <li><link to="/about">about</link></li> <li><link to="/inbox">inbox</link></li> </ul> {this.props.children} </p> ); } } const about = () => ( <p> <h3>about</h3> </p> ) const home = () => ( <p> <h3>home</h3> </p> ) const message = ({ match }) => ( <p> <h3>new messages</h3> <h3>{match.params.id}</h3> </p> ) const inbox = ({ match }) => ( <p> <h2>topics</h2> <route path={`${match.url}/messages/:id`} component={message}/> </p> ) reactdom.render( (<hashrouter> <app> <route exact path="/" component={home} /> <route path="/about" component={about} /> <route path="/inbox" component={inbox} /> </app> </hashrouter>), document.getelementbyid('root') );
相关推荐:
vue router动态路由和嵌套路由实例详解
用路由延迟加载angular模块方法
vue-router2实现路由功能实例讲解
以上就是react router 4.0以上的路由如何应用的详细内容。
其它类似信息

推荐信息