react router 4.0以上的路由應用詳解
本文介紹了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') );
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于React.js實現(xiàn)原生js拖拽效果引發(fā)的思考
這篇文章主要為大家詳細介紹了基于React.js實現(xiàn)原生js拖拽效果,繼而引發(fā)的一系列思考,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-03-03D3.js(v3)+react 實現(xiàn)帶坐標與比例尺的散點圖 (V3版本)
散點圖(Scatter Chart),通常是一橫一豎兩個坐標軸,數(shù)據(jù)是一組二維坐標,分別對應兩個坐標軸,與坐標軸對應的地方打上點。由此可以猜到,需要的元素包括circle(圓)和axis(坐標軸),接下來通過本文大家分享D3.js(v3)+react 實現(xiàn)帶坐標與比例尺的散點圖 (V3版本) ,一起看看2019-05-05淺析JS中什么是自定義react數(shù)據(jù)驗證組件
我們在做前端表單提交時,經(jīng)常會遇到要對表單中的數(shù)據(jù)進行校驗的問題。這篇文章主要介紹了js中什么是自定義react數(shù)據(jù)驗證組件,需要的朋友可以參考下2018-10-10react?hooks頁面實時刷新方式(setInterval)
這篇文章主要介紹了react?hooks頁面實時刷新方式(setInterval),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03ReactHooks批量更新state及獲取路由參數(shù)示例解析
這篇文章主要介紹了React Hooks如何實現(xiàn)批量更新state以及獲取路由參數(shù)的示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-10-10React-Route6實現(xiàn)keep-alive效果
本文主要介紹了React-Route6實現(xiàn)keep-alive效果,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧<BR>2022-06-06