首页 > 语言 > JavaScript > 正文

详解升级react-router 4 踩坑指南

2024-05-06 15:13:00
字体:
来源:转载
供稿:网友

一.前言

上午把近日用React做的一个新闻项目所依赖的包升级到了最新的版本,其中从react-router(2.8.1)升级到react-router(4.1.2)中出现了很多问题, 故总结一下在升级过程中遇到的问题.

二.react-router,V4版本修改内容

1. 所有组件更改为从react-router-dom导入

之前的所有路由组件均是从react-router中导入,在我之前的项目中,导入相关组件如下:

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

在react-router4 开始,所有的router组件均是从react-router-dom中导入, 所以一下的需要更改为以下代码:

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

细心的你发现在,到导入的过程中,我删除了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>

现在需要更改为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>

细心的你发现,这里的代码不仅仅是将Router替换为BrowserRouter,而且还把所有的Route中用Switch包裹起来. 下面就是v4的另一个修改.

3. <BrowserRouter>只能有一个子节点

<BroserRouter>只能有一个子节点,所以官网建议的是使用<Switch>进行包裹,官网给出的例子如下.

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', 这是更改之后最坑的地方!!! 因为其他的更改,在控制台都会有着详细的错误提示, 然而找不到文件只会出现404!!!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选