欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

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

时间:2021-02-09 14:30:55|栏目:JavaScript代码|点击:

本文介绍了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')
);

上一篇:微信小程序实现星级评分和展示

栏    目:JavaScript代码

下一篇:javascript处理表单示例(javascript提交表单)

本文标题:react router 4.0以上的路由应用详解

本文地址:http://www.codeinn.net/misctech/59584.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有