參考文檔:https://reacttraining.com/react-router/web/api/withRouter
有的時候項目中需要根據路由對模塊進行處理,所以需要實時獲取到路由的狀態,
如下圖:
在點擊切換路由的時候下面的文字會跟着變化
具體代碼如下:
import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";
class ShowTheLocation extends React.Component{
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
};
render() {
const { match, location, history } = this.props;
return <h1>You are now at {location.pathname}</h1>;
}
}
這樣就能實時獲取更新路由了