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}
<button onClick={() => this.replaceSee(m)}>replace查看</button>
<button onClick={() => this.pushSee(m)}>push查看</button>
</li>
))
}
</ul>
<hr />
<Route path='/home/message/detail' component={Detail} />
<button onClick={this.back}>回退</button>
<button onClick={this.forward}>前进</button>
<button onClick={this.go}>go</button>
</div>
)
}
}