在React中使用react-router-dom路由

在React中使用react-router-dom路由

使用React构建的单页面应用,要想实现页面间的跳转,首先想到的就是使用路由。在React中,常用的有两个包可以实现这个需求,那就是react-router和react-router-dom。本文主要针对react-router-dom进行说明。

安装

首先进入项目目录,使用npm安装react-router-dom:

npm install react-router-dom --save-dev //这里可以使用cnpm代替npm命令

基本操作

然后我们新建两个页面,分别命名为“home”和“detail”。在页面中编写如下代码:

import React from 'react';


export default class Home extends React.Component {
    render() {
        return (
            <div>
                <a>去detail</a>
            </div>
        )
    }
}

home.js

import React from 'react';


export default class Home extends React.Component {
    render() {
        return (
            <div>
                <a>回到home</a>
            </div>
        )
    }
}

detail.js

然后再新建一个路由组件,命名为“Router.js”,并编写如下代码:

import React from 'react';
import {HashRouter, Route, Switch} from 'react-router-dom';
import Home from '../home';
import Detail from '../detail';


const BasicRoute = () => (
    <HashRouter>
        <Switch>
            <Route exact path="/" component={Home}/>
            <Route exact path="/detail" component={Detail}/>
        </Switch>
    </HashRouter>
);


export default BasicRoute;

如上代码定义了一个纯路由组件,将两个页面组件Home和Detail使用Route组件包裹,外面套用Switch作路由匹配,当路由组件检测到地址栏与Route的path匹配时,就会自动加载响应的页面。
然后在入口文件中——我这里指定的是index.js——编写如下代码:

import React from 'react';
import ReactDOM from 'react-dom';
import Router from './router/router';

ReactDOM.render(
  <Router/>,
  document.getElementById('root')
);

这里相当于向页面返回了一个路由组件。我们先运行项目看一下效果,在地址栏输入“http://localhost:3000/#/”:

home.js

输入“http://localhost:3000/#/detail”:

detail.js

通过a标签跳转

可以看到其实路由已经开始工作了,接下来我们再来做页面间的跳转。在home.js和detail.js中,我们修改如下代码:

import React from 'react';


    export default class Home extends React.Component {
        render() {
            return (
                <div>
                <a href='#/detail'>去detail</a>
            </div>
        )
    }
}

home.js

import React from 'react';


export default class Home extends React.Component {
    render() {
        return (
            <div>
                <a href='#/'>回到home</a>
            </div>
        )
    }
}

detail.js
重新打包运行,在浏览器地址栏输入“http://localhost:3000/”,试试看页面能否正常跳转。如果不能,请按步骤一步一步检查代码是否有误。以上是使用a标签的href进行页面间跳转,此外react-router-dom还提供了通过函数的方式跳转页面。

通过函数跳转

首先我们需要修改router.js中的两处代码:

...
import {HashRouter, Route, Switch, hashHistory} from 'react-router-dom';
...
<HashRouter history={hashHistory}>
...

然后在home.js中:
import React from 'react';

export default class Home extends React.Component {
    constructor(props) {
        super(props);
    }
    
    
    render() {
        return (
            <div>
                <a href='#/detail'>去detail</a>
                <button onClick={() => this.props.history.push('detail')}>通过函数跳转</button>
            </div>
        )
    }
}

在a标签下面添加一个按钮并加上onClick事件,通过this.props.history.push这个函数跳转到detail页面。在路由组件中加入的代码就是将history这个对象注册到组件的props中去,然后就可以在子组件中通过props调用history的push方法跳转页面。

很多场景下,我们还需要在页面跳转的同时传递参数,在react-router-dom中,同样提供了两种方式进行传参。

url传参

在router.js中,修改如下代码:

...
<Route exact path="/detail/:id" component={Detail}/>
...

然后修改detail.js,使用this.props.match.params获取url传过来的参数:

...
componentDidMount() {
    console.log(this.props.match.params);
}
...

在地址栏输入“http://localhost:3000/#/detail/3”,打开控制台:

可以看到传过去的id=3已经被获取到了。react-router-dom就是通过“/:”去匹配url传递的参数。

隐式传参

此外还可以通过push函数隐式传参。

修改home.js代码如下:

import React from 'react';


export default class Home extends React.Component {
    constructor(props) {
        super(props);
    }
    
    
    render() {
        return (
            <div>
                <a href='#/detail/3'>去detail</a>
                    <button onClick={() => this.props.history.push({
                        pathname: '/detail',
                        state: {
                            id: 3
                        }
                })}>通过函数跳转</button>
            </div>
        )
    }
}

在detail.js中,就可以使用this.props.history.location.state获取home传过来的参数:

componentDidMount() {
    //console.log(this.props.match.params);
    console.log(this.props.history.location.state);
}

跳转后打开控制台可以看到参数被打印:

其他函数

replace

有些场景下,重复使用push或a标签跳转会产生死循环,为了避免这种情况出现,react-router-dom提供了replace。在可能会出现死循环的地方使用replace来跳转:

this.props.history.replace('/detail');

goBack

场景中需要返回上级页面的时候使用:

this.props.history.goBack();

总结

这篇文章基本上涵盖了大部分react-router-dom的用法,此后再发现有什么遗漏我会再继续补充。



作者:aimmarc
链接:https://www.jianshu.com/p/8954e9fb0c7e
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React Router是一个用于建立SPA应用程序的库,它提供了一种将应用程序状态与URL同步的方式。React Router v6是React Router的最新版本,它引入了一些新的概念和语法。 下面是使用React Router v6搭建路由的步骤: 1. 安装React Router v6 使用npm或者yarn安装React Router v6: ``` npm install react-router-dom@next ``` 2. 创建路由 在应用程序的入口文件使用BrowserRouter创建一个路由: ```jsx import { BrowserRouter } from 'react-router-dom'; ReactDOM.render( <BrowserRouter> <App /> </BrowserRouter>, document.getElementById('root') ); ``` 3. 定义路由 使用Route组件定义路由。Route组件的path属性指定URL的路径,component属性指定该路径对应的组件: ```jsx import { Route } from 'react-router-dom'; function App() { return ( <div> <Route path="/" component={Home} /> <Route path="/about" component={About} /> </div> ); } ``` 在上面的例子,当URL路径为“/”时,渲染Home组件;当URL路径为“/about”时,渲染About组件。 4. 处理404页面 使用Route组件的exact属性确保路由匹配完全相等的路径。这样可以避免在匹配“/”路径时同时匹配到所有其他路径。 使用Route组件的path属性指定“*”路径,即匹配所有路径的路径。将这个Route组件放在所有其他Route组件的下面,就可以为未匹配到任何路径的URL显示404页面: ```jsx import { Route, Routes } from 'react-router-dom'; function App() { return ( <div> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="*" element={<NotFound />} /> </Routes> </div> ); } ``` 在上面的例子,当URL路径为任何未匹配到的路径时,渲染NotFound组件。 5. 嵌套路由 使用Routes组件嵌套Route组件,可以创建嵌套路由。在嵌套路由,父级Route组件的path属性包含所有子级Route组件的path属性的前缀。 ```jsx import { Route, Routes } from 'react-router-dom'; function App() { return ( <div> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />}> <Route path="team" element={<Team />} /> <Route path="history" element={<History />} /> </Route> <Route path="*" element={<NotFound />} /> </Routes> </div> ); } ``` 在上面的例子,当URL路径为“/about/team”时,渲染Team组件;当URL路径为“/about/history”时,渲染History组件。 React Router v6引入了一些新的语法,例如使用Routes组件代替Router组件,使用element属性代替component属性等。这些语法的目的是让React Router更加简洁易用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值