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') );

参考

  • https://stackoverflow.com/questions/42845834/why-can-i-not-nest-route-components-in-react-router-4-x

  • https://code.tutsplus.com/tutorials/understanding-nested-routing-in-react–cms-27955

转载于:https://www.cnblogs.com/sylarmeng/p/6920903.html

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