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

本文介绍了react router 4.0以上的路由应用,分享给大家,具体如下:

在4.0以下的react router中,嵌套的路由可以放在一个router标签中,形式如下,嵌套的路由也直接放在一起。


  
  
   
  

但是在4.0以后,嵌套的路由与之前的就完全不同了,需要单独放置在嵌套的根component中去处理路由,否则会一直有warning:

You should not use and in the same route

正确形式如下


  
  
   //
  

上面将嵌套的路由注释掉

const Users = ({ match }) => (
 

Topics

)

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

App

  • Home
  • About
  • Inbox
{this.props.children}
); } } const About = () => (

About

) const Home = () => (

Home

) const Message = ({ match }) => (

new messages

{match.params.id}

) const Inbox = ({ match }) => (

Topics

) ReactDOM.render( ( ), document.getElementById('root') );

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

你可能感兴趣的:(react router 4.0以上的路由应用详解)