withRouter
React Router DOM 提供了一个withRouter()
方法,用于向普通组件中注入 History 对象、Location 描述对象和路由路径 Match 描述对象。withRouter()
会从距离被包装组件最近的路由组件中取得上述值供使用。使用withRouter()
函数包装的组件会返回一个新的组件(高阶组件)。
import React from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router';
class ShowTheLocation extends React.Component {
render() {
const { match, location, history } = this.props;
return <div>You are now at {location.pathname}</div>;
}
}
const ShowTheLocationWithRouter = withRouter(ShowTheLocation);