使用 withRouter() 时如何获取路由上下文,位置,参数等?
import { withRouter } from 'react-router'; const SomeComponent = ({location, route, params}) => ( <h1>The current location is {location.pathname}</h1> ); const ComposedWithRouter = withRouter(SomeComponent);
您可以使用withRouter获得该信息,还是必须将这些内容显式传递到组件树中?
因此,不再使用context。在道具中都可以使用:
context
SomeComponent.propTypes = { location: React.PropTypes.shape({ pathname: React.PropTypes.string, query: React.PropTypes.shape({ ... }) }), params: React.PropTypes.shape({ ... }), router: React.PropTypes.object } const ComposedWithRouter = withRouter(SomeComponent);
因此,假设SomeComponent您想将用户转到新路线,您只需this.props.router.push('someRoute')
SomeComponent
this.props.router.push('someRoute')