国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

詳解升級react-router 4 踩坑指南

2024-05-06 15:13:00
字體:
供稿:網(wǎng)友

一.前言

上午把近日用React做的一個新聞項目所依賴的包升級到了最新的版本,其中從react-router(2.8.1)升級到react-router(4.1.2)中出現(xiàn)了很多問題, 故總結(jié)一下在升級過程中遇到的問題.

二.react-router,V4版本修改內(nèi)容

1. 所有組件更改為從react-router-dom導(dǎo)入

之前的所有路由組件均是從react-router中導(dǎo)入,在我之前的項目中,導(dǎo)入相關(guān)組件如下:

//v2import {Router,Route,hashHistory} from 'react-router';

在react-router4 開始,所有的router組件均是從react-router-dom中導(dǎo)入, 所以一下的需要更改為以下代碼:

//v4import {Route,BrowserRouter, Switch} from 'react-router-dom';

細心的你發(fā)現(xiàn)在,到導(dǎo)入的過程中,我刪除了Router,但是增加了BorwerRouter和Switch,下面我會一步步的說明.

2. 將所有<Router>替換為<BrowserRouter>

之前v2中的代碼如下:

//v2 <Router history={hashHistory}>  <Route path="/" component={PCIndex}></Route>  <Route path="/details/:uniqueky" component={PCNewsDetails}></Route>  <Route path="/usercenter" component={PCUserCenter}></Route> </Router>

現(xiàn)在需要更改為BrowserRouter

//v4<BrowserRouter>  <Switch>   <Route exact path="/" component={MobileIndex}></Route>   <Route path="/details/:uniqueky" component={MobileNewsDetails}></Route>   <Route path="/usercenter" component={MobileUserCenter}></Route>  </Switch> </BrowserRouter>

細心的你發(fā)現(xiàn),這里的代碼不僅僅是將Router替換為BrowserRouter,而且還把所有的Route中用Switch包裹起來. 下面就是v4的另一個修改.

3. <BrowserRouter>只能有一個子節(jié)點

<BroserRouter>只能有一個子節(jié)點,所以官網(wǎng)建議的是使用<Switch>進行包裹,官網(wǎng)給出的例子如下.

In v3, you could specify a number of child routes, and only the first one that matched would be rendered.

// v3<Route path='/' component={App}> <IndexRoute component={Home} /> <Route path='about' component={About} /> <Route path='contact' component={Contact} /></Route>

v4 provides a similar functionality with the <Switch> component. When a <Switch> is rendered, it will only render the first child <Route> that matches the current location.

// v4const App = () => ( <Switch>  <Route exact path='/' component={Home} />  <Route path='/about' component={About} />  <Route path='/contact' component={Contact} /> </Switch>)

4. 最坑的地方:在當前目錄下的文件路徑不再使用./, 而是直接用/.

在進行文件引用的時候 ,./src/js的寫法需要更改文'/src/js', 這是更改之后最坑的地方!!! 因為其他的更改,在控制臺都會有著詳細的錯誤提示, 然而找不到文件只會出現(xiàn)404!!!

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 冷水江市| 囊谦县| 渝北区| 寿光市| 屏边| 松阳县| 光山县| 无为县| 永年县| 南投市| 穆棱市| 寻甸| 江孜县| 雷波县| 武城县| 宜阳县| 盐池县| 灯塔市| 高清| 新疆| 建湖县| 于都县| 宜丰县| 阿坝| 凉城县| 玉屏| 海丰县| 宁强县| 玉溪市| 金川县| 保定市| 高碑店市| 舟曲县| 西吉县| 淄博市| 东明县| 紫金县| 潜山县| 伊通| 江源县| 密云县|