This article mainly introduces to you the detailed explanation of routing application of react router 4.0 and above. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
In react router below 4.0, nested routes can be placed in a router tag, in the following form, and nested routes are also placed directly together.
<Route component={App}> <Route path="groups" components={Groups} /> <Route path="users" components={Users}> <Route path="users/:userId" component={Profile} /> </Route> </Route>
But after 4.0, the nested routing is completely different from the previous one. It needs to be placed separately in the nested root component to process the routing. Otherwise there will always be a warning:
You should not use
The correct form is as follows
<Route component={App}> <Route path="groups" components={Groups} /> <Route path="users" components={Users}> //<Route path="users/:userId" component={Profile} /> </Route> </Route>
Comment out the nested routing above
const Users = ({ match }) => ( <p> <h2>Topics</h2> <Route path={`${match.url}/:userId`} component={Profile}/> </p> )
Add a new route in the component that requires nested routing
A complete example of nested routing is as follows
Instructions and precautions
1. The following code is in ES6 format
2 The .react-router-dom version is 4.1.1
3. Please pay attention to using history such as HashRouter, otherwise there will always be a warning and cannot be rendered
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 ( <p> <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} </p> ); } } const About = () => ( <p> <h3>About</h3> </p> ) const Home = () => ( <p> <h3>Home</h3> </p> ) const Message = ({ match }) => ( <p> <h3>new messages</h3> <h3>{match.params.id}</h3> </p> ) const Inbox = ({ match }) => ( <p> <h2>Topics</h2> <Route path={`${match.url}/messages/:id`} component={Message}/> </p> ) ReactDOM.render( (<HashRouter> <App> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> <Route path="/inbox" component={Inbox} /> </App> </HashRouter>), document.getElementById('root') );
Related recommendations:
detailed explanation of vue router dynamic routing and nested routing examples
Lazy loading with routing Angular module method
Vue-Router2 implementation of routing function example explanation
The above is the detailed content of How to apply routing in react router 4.0 or above. For more information, please follow other related articles on the PHP Chinese website!