鍍金池/ 問答/HTML/ React Router 4.0后使用js代碼控制路由跳轉(zhuǎn)的方法

React Router 4.0后使用js代碼控制路由跳轉(zhuǎn)的方法

現(xiàn)在需要用react實現(xiàn)一個需求,每當(dāng)頁面請求鏈接/跳轉(zhuǎn)時需要向服務(wù)器驗證當(dāng)前登錄態(tài),請求鏈接的函數(shù)封裝在一個叫request.js的工具里(非組件),當(dāng)返回鑒權(quán)失敗時需要跳轉(zhuǎn)到錯誤頁面,要求不使用window.location.href方法,因為需要傳遞參數(shù)但不得暴露,4.0版本前有hashHistory可以實現(xiàn)類似的功能,那么4.0版本之后要怎么辦呢?

回答
編輯回答
慢半拍

使用 withRouter
withRouter高階組件,提供了history讓你使用~

import React from "react";
import {withRouter} from "react-router-dom";

class MyComponent extends React.Component {
...
myFunction() {
this.props.history.push("/some/Path");
}
...
}
export default withRouter(MyComponent);

這樣就好了

2018年9月18日 14:19