react-router 路由控制頁面跳轉
阿新 • • 發佈:2019-01-01
剛接觸react,路由使用的react-router 4.0。對於路由在頁面中的跳轉,使用了兩種方法
1,使用widthRouter,他是一個高階元件,他提供了history讓我們使用。
eg:返回上一個頁面,下面是我的實現程式碼。
import React,{Component} from 'react' import {withRouter} from 'react-router-dom' import '../../common/css/iconfont.css' import '../../common/css/head.css' class HeadBack extends Component{constructor(){ super() } goback(){ this.props.history.goBack() } render(){ return( <div className="head-wrapper"> <div className="head-box"> <div className="head-left"> <i className="iconfont icon-common-fanhui-copy"onClick={()=>this.goback()}></i> </div> <div className="head-right"> <div className="head">{this.props.title}</div> </div> </div> </div> )} } export default withRouter(HeadBack);
2,使用createBrowserHistory
eg:部分程式碼片段
import React,{Component} from 'react'
import {createBrowserHistory} from 'history'
const history = createBrowserHistory()
class myComponent extends Component{
constructor(){
super();
}
componentDidMount(){
fetch('url',{
method:'get/post'
}).then(res => res.json())
.then(res => {
this.props.history.push("/")
})
}
render(){
return(
<div className="container">
</div>
)
}
}
export default myComponent
以上程式碼僅供參考