手動(dòng)控制路由跳轉(zhuǎn),其實(shí)就是使用history來(lái)控制路由跳轉(zhuǎn)的寓娩。疮茄。。
react-router v3我沒(méi)用過(guò)根暑,所以就不做比較了
1. 使用 withRouter
引入withRouterimport { withRouter } from "react-router-dom"
然后用高階組件withRouter把要導(dǎo)出的組件傳入進(jìn)去
最后使用this.props.history.push()
把你需要跳轉(zhuǎn)的路由push進(jìn)去就好了
-
例子
import React from "react";
import { withRouter } from "react-router-dom";
import { message, Popconfirm } from "antd";
import "../css/feedback.css";
class Logout extends React.Component {
constructor(props) {
super(props);
}
confirm = () => {
this.props.history.push("/");
};
cancel = () => {
message.error("Click on No");
};
render() {
return (
<div>
<Popconfirm
title="確定要退出登錄嗎?"
onConfirm={this.confirm}
onCancel={this.cancel}
okText="退出"
cancelText="取消"
>
<a>注銷(xiāo)</a>
</Popconfirm>
</div>
);
}
}
export default withRouter(Logout);
2.使用context
這個(gè)方法不太推薦,因?yàn)楣俜揭膊煌扑]徙邻,可能在react未來(lái)的版本會(huì)被廢除
重點(diǎn)在這三段中
import PropTypes from "prop-types";
static contextTypes = {
router: PropTypes.object
}
this.context.router.history.push("/"); //把你需要跳轉(zhuǎn)的路由push進(jìn)去
import React from "react";
import PropTypes from "prop-types";
import { message, Popconfirm } from "antd";
import "../css/feedback.css";
class Logout extends React.Component {
static contextTypes = {
router: PropTypes.object
}
constructor(props) {
super(props);
}
confirm = () => {
this.context.router.history.push("/");
};
cancel = () => {
message.error("Click on No");
};
render() {
return (
<div>
<Popconfirm
title="確定要退出登錄嗎?"
onConfirm={this.confirm}
onCancel={this.cancel}
okText="退出"
cancelText="取消"
>
<a>注銷(xiāo)</a>
</Popconfirm>
</div>
);
}
}
export default Logout;
3.自己創(chuàng)建history
這是我個(gè)人比較喜歡也比較推薦的用法
import createHistory from 'history/createBrowserHistory';
export default createHistory();
在其他頁(yè)面我們就可以引入history排嫌,注意下路徑
import history from './history';
const skip = () => {
history.push("/");
}