欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

react router 4.0以上的路由应用详解

程序员文章站 2023-10-28 18:07:58
本文介绍了react router 4.0以上的路由应用,分享给大家,具体如下: 在4.0以下的react router中,嵌套的路由可以放在一个router标签中,...

本文介绍了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 }) => (
 <div>
  <h2>topics</h2>
  <route path={`${match.url}/:userid`} component={profile}/>
 </div>
) 

上面在需要嵌套路由的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 (
   <div>
    <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}

   </div>
  );
 }
}

const about = () => (
 <div>
  <h3>about</h3>
 </div>
)

const home = () => (
 <div>
  <h3>home</h3>
 </div>
)

const message = ({ match }) => (
 <div>
  <h3>new messages</h3>
  <h3>{match.params.id}</h3>
 </div>
)

const inbox = ({ match }) => (
 <div>
  <h2>topics</h2>
  <route path={`${match.url}/messages/:id`} component={message}/>

 </div>
) 

reactdom.render(
 (<hashrouter>
  <app>
    <route exact path="/" component={home} />
    <route path="/about" component={about} />
    <route path="/inbox" component={inbox} />
  </app>
 </hashrouter>),
 document.getelementbyid('root')
);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。