温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

react router 4.0以上路由应用的示例分析

发布时间:2021-08-30 11:45:55 来源:亿速云 阅读:104 作者:小新 栏目:web开发

小编给大家分享一下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>
  <h3>Topics</h3>
  <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>
    <h2>App</h2>
    <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>
  <h4>About</h4>
 </div>
)

const Home = () => (
 <div>
  <h4>Home</h4>
 </div>
)

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

const Inbox = ({ match }) => (
 <div>
  <h3>Topics</h3>
  <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')
);

看完了这篇文章,相信你对“react router 4.0以上路由应用的示例分析”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI