React中使用react-router-dom路由

安装
首先进入项目目录,使用npm安装react-router-dom:
npm install react-router-dom --save-dev //这里可以使用cnpm代替npm命令
新建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;
index.js 入口页
import React from 'react';
import ReactDOM from 'react-dom';
import Router from './router/router';

ReactDOM.render(
  <Router/>,
  document.getElementById('root')
);
通过a标签跳转
import React from 'react';


    export default class Home extends React.Component {
        render() {
            return (
                <div>
                <a href='#/detail'>去detail</a>
            </div>
        )
    }
}
通过函数跳转
router.js 修改
...
import {HashRouter, Route, Switch, hashHistory} from 'react-router-dom';
...
<HashRouter history={hashHistory}>
...
跳转页
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>
        )
    }
}
url传参
router.js 修改
...
<Route exact path="/detail/:id" component={Detail}/>
...
<Link to="/detail/123">用户</Link>
hashHistory.push("/user/123");
detail.js中使用this.props.match.params获取url传过来的参数:
...
componentDidMount() {
    console.log(this.props.match.params);
}
...
隐式传参
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传过来的参数:
state方式依然可以传递任意类型的数据,而且可以不以明文方式传输。
var data = {id:3,name:sam,age:36};
var path = {
  pathname:'/user',
  query:data,
}
var data = this.props.location.query;
query方式可以传递任意类型的值,但是页面的URL也是由query的值拼接的,URL很长
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();
嵌套路由
import React from 'react';
import './MainLayout.scss';

const { Header, Sider, Content } = Layout;


export default class MainLayout extends React.Component {

    render() {
        return (
            <div className='main-layout'>
                父组件
            </div>
        );
    }
}
import React, {useState} from 'react';
import {Modal, Select} from "antd";
import {connect} from 'react-redux';
import {addCount} from '../../servers/home';


function Home(props) {
    const [visible, setVisible] = useState(false);
    const {countNum: {count}, dispatch} = props;

    return (
        <div>
            子组件
        </div>
    )
}
router.js
export default Home;
import React from 'react';
import {HashRouter, Route, Switch} from "react-router-dom";
import Home from '../pages/Home/Home';
import MainLayout from '../layout/MainLayout';

const BasicRouter = () => (
    <HashRouter>
        <Switch>
            <Route path="/index" component={
                <MainLayout>
                  <Route exact path="/" component={Home}/>
                  <Route exact path="/index" component={Home}/>
                  <Route path="/index/home" component={Home}/>
                </MainLayout>
             }/>
        </Switch>
    </HashRouter>
);


export default BasicRouter;

//可能出现的问题
1、Attempted import error: 'hashHistory' is not exported from 'react-router'.


import { HashRouter as Router, Route, hashHistory } from 'react-router-dom'
页面就会报错Attempted import error: 'hashHistory' is not exported from 'react-router'.

//原因react-router4现在不支持hashHistory了,解决办法如下:

import createHashHistory from 'history/createHashHistory';
const hashHistory = createHashHistory();
//但是又提示Warning: Please use require("history").createHashHistory instead of require("history/createHashHistory"). Support for the latter will be removed in the next major release.如下改一下:
import { createHashHistory } from 'history';
const hashHistory = createHashHistory();
//此时 Warning: <HashRouter> ignores the history prop. To use a custom history, use import { Router } instead of import { HashRouter as Router }.
//OK,暂时解决眼前的问题。


2、Cannot read property 'push' of undefined
在父子组件上,在父组件调用子组件定义的跳转事件时,要传递history

父组件

<BottomBar
    history={this.props.history}
/>
子组件

<div
    onClick={()=>{
        this.props.history.push(`/path`);
    }}
>
    child
</div>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值