首先,您不需要这样做,var r = this;因为它使用的if statement是回调本身的上下文,因为您使用的是箭头功能,因此它是指React组件的上下文。
根据文档:
历史记录对象通常具有以下属性和方法:
因此,在导航时,您可以将道具传递给历史对象,例如
this.props.history.push({
pathname: '/template',
search: '?query=abc',
state: { detail: response.data }
})
或类似地对于一个Link或多个Redirect组件
<Link to={{
pathname: '/template',
search: '?query=abc',
state: { detail: response.data }
}}> My Link </Link>
然后在使用/templateroute 渲染的组件中,您可以访问像
this.props.location.state.detail
另外请记住,在使用道具中的历史记录或位置对象时,您需要将组件与相连withRouter。
根据文档:
与路由器
您可以<Route>'s通过withRouter高阶组件访问历史对象的属性和最接近的
匹配项。withRouter
每当路线更改时,都会使用与<Route>render 相同的props重新渲染其组件props: { match, location, history }。
Route应该有机会获得this.props.location,this.props.history等等。我觉得你不需要使用ref与V4了。尝试做this.props.history.push('/template');