十、【React-Router5】编程式路由导航

本文介绍了React中编程式路由导航的原理,通过this.props.history对象的API实现页面跳转、前进、后退及刷新。示例代码详细展示了如何在Messages组件中运用这些方法,并提供了Detail组件的调用方式。同时,文章还提供了实际操作的效果展示。
摘要由CSDN通过智能技术生成

1、编程式路由导航原理

  • 借助 this.prosp.history 对象上的API对操作路由跳转、前进、后退
    • this.prosp.history.push()
    • this.prosp.history.replace()
    • this.prosp.history.goBack()
    • this.prosp.history.goForward()
    • this.prosp.history.go()
      • 正数向前n步,负数后退n步,0刷新页面

2、实现效果

在这里插入图片描述

3、修改上上节代码

点击访问 上上节代码;有点套娃,请耐心查看

项目结构不变,只修改了 Messages.jsx

3.1、CODE(Messages.jsx)

此例子只写了最常用的 state 传参格式,其余如有需要请自测

import React, { Component } from 'react'
import { Link, Route } from 'react-router-dom'
import Detail from './Detail/item'

export default class Message extends Component {
    state = {
        messages: [{
            id: '001',
            title: '小道消息',
            info: '这是一个小道消息'
        }, {
            id: '002',
            title: '大道消息',
            info: '这是一个大道消息,非常大!!!'
        }, {
            id: '003',
            title: '大道消息Plus',
            info: '这是大道消息Plus,非常Plus!!!'
        }]
    }

    replaceSee = msg => {
        this.props.history.replace({
            pathname: '/home/message/detail',
            state: msg
        })
    }

    pushSee = msg => {
        this.props.history.push({
            pathname: '/home/message/detail',
            state: msg
        })
    }

    back = () => {
        this.props.history.goBack()
    }

    forward = () => {
        this.props.history.goForward()
    }

    go = () => {
        this.props.history.go(-2)
    }

    render() {
        return (
            <div>
                <ul>
                    {
                        this.state.messages.map(m => (
                            <li key={m.id}>
                                {m.title}
                                &nbsp;&nbsp;
                                <button onClick={() => this.replaceSee(m)}>replace查看</button>
                                &nbsp;&nbsp;
                                <button onClick={() => this.pushSee(m)}>push查看</button>
                            </li>
                        ))
                    }
                </ul>
                <hr />
                <Route path='/home/message/detail' component={Detail} />

                <button onClick={this.back}>回退</button>&nbsp;
                <button onClick={this.forward}>前进</button>&nbsp;
                <button onClick={this.go}>go</button>
            </div>
        )
    }
}

3.2、Result

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

纯纯的小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值