使用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
。这一切都可以在 Prop 中找到:
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')
关于reactjs - 使用 React Router 和 Router,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39174814/