withRouter
You can get access to the history object’s properties and the closest 's match via the withRouter higher-order component.
withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.
可以使用withRouter这个高阶组件获取到history对象
withRouter会在render时把更新后的match, location和history传递给被包裹组件
例子
import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";
// A simple component that shows the pathname of the current location
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 <div>You are now at {location.pathname}</div>;
}
}
// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation);
重要提示
Important Note
withRouter does not subscribe to location changes like React Redux’s connect does for state changes. Instead, re-renders after location changes propagate out from the component. This means that withRouter does not re-render on route transitions unless its parent component re-renders. If you are using withRouter to prevent updates from being blocked by shouldComponentUpdate, it is important that withRouter wraps the component that implements shouldComponentUpdate.
withRouter不会像react redux中的connect方法一样订阅location的变化,而是在loaction变化从组件传播出去之后触发re-render。
这意味着withRouter不会在路由变换时re-render除非它的父组件re-render。
如果想用shouldComponentUpdate来阻止组件更新,需要将withRouter包裹实现shouldComponentUpdate方法的组件
举个栗子:
// This gets around shouldComponentUpdate
withRouter(connect(...)(MyComponent))
// or
compose(
withRouter,
connect(...)
)(MyComponent)
// This does not
connect(...)(withRouter(MyComponent))
// nor
compose(
connect(...),
withRouter
)(MyComponent)