请先查看第一篇
https://blog.csdn.net/oracle8090/article/details/112368060
1.实现使用按钮跳转路由
this.props.history.push("/cart")
this.props.history.replace("/cart")
push和replace的区别:push添加,replace是替换页面,主要体现,是否可以回退
在原有项目的基础上增加Cart 页面
import React from 'react'
import Nav from '../Nav'
export default class Cart extends React.Component{
render(){
return(
<div>
<Nav/>
Cart
</div>
)
}
}
添加Nav链接
在app.js页面添加路由
修改home页面
实现用按钮跳转
2.、路由的作用域
被路由直接管理的对象,存在history,否则则不存在,解决方案:可以传递history
<Computer history={ this.props.history }/>
this.props.history.push("/");
如添加
import React from 'react'
export default class Computer extends React.Component{
clickHandle=()=>{
this.props.history.push("/")
}
render(){
return(
<div>
<button onClick={this.clickHandle}>去首页</button>
</div>
)
}
}
在cart中引用
不要在Nav/index 和 App.js中配置
点击去首页会报错
原因是只有被路由管理的页面才有history 需要做以下修改
3.基于第二步的修改 使用高级组件
创建Game页面
import React from 'react'
import {withRouter} from 'react-router-dom'
class Game extends React.Component{
clickHandle=()=>{
this.props.history.push("/")
}
render(){
return(
<div>
<button onClick={this.clickHandle}>game 去首页</button>
</div>
)
}
}
//高级组件
export default withRouter(Game)
在 computer中直接引用game,不需要传递history就可以直接进行路由的跳转