更新时间:2023-01-13 23:41:22
当你在你的应用中包含一个主页面组件时,它通常被包裹在一个
组件中,如下所示:
When you include a main page component in your app, it is often wrapped in a <Route>
component like this:
<Route path="/movies" component={MoviesIndex} />
通过这样做,MoviesIndex
组件可以访问 this.props.history
,因此它可以使用 this.props.history.push.
By doing this, the MoviesIndex
component has access to this.props.history
so it can redirect the user with this.props.history.push
.
某些组件(通常是页眉组件)出现在每个页面上,因此没有包含在
中:
Some components (commonly a header component) appear on every page, so are not wrapped in a <Route>
:
render() {
return (<Header />);
}
这意味着标头无法重定向用户.
This means the header cannot redirect the user.
为了解决这个问题,header 组件可以被包裹在一个 withRouter
函数,无论是在导出时:
To get around this problem, the header component can be wrapped in a withRouter
function, either when it is exported:
export default withRouter(Header)
这使 Header
组件可以访问 this.props.history
,这意味着标题现在可以重定向用户.
This gives the Header
component access to this.props.history
, which means the header can now redirect the user.