Som*_*ium 4 javascript web reactjs react-router react-redux
目前,我创建了一个搜索栏,并将我的搜索栏链接到我的搜索结果,如下所示:
render() {
if (this.props.itemsFetchSuccess) {
return (
<Redirect to={{
pathname: '/search',
search: `?item-name=${this.props.searchQuery}`
}} />
);
Run Code Online (Sandbox Code Playgroud)
作为我的搜索栏渲染组件的一部分。
GOOGLE CHROME 主 -> 主登陆 -> 搜索结果。
但我怀疑因为我在 React-Router v4 中使用了重定向标签,所以它没有将它添加到浏览器历史堆栈中。如果我从搜索结果页面按回浏览器,它不会返回之前的页面(即主登陆),但会返回主登陆之前的页面。
有没有更好的方法来做到这一点,因为我也尝试使用 Link 标签,但这不起作用,因为它只是生成链接,并且在搜索结果完成后实际上并不重定向。
谢谢!
在您的情况下,您可以将 Redirect 与push参数一起使用。当按下后退按钮时,它将正确重定向到上一页。
*推:布尔
当为 true 时,重定向会将新条目推送到历史记录中,而不是替换当前条目。
<Redirect push to={{
pathname: '/search',
search: `?item-name=${this.props.searchQuery}`
}} />
Run Code Online (Sandbox Code Playgroud)
Redirect覆盖当前条目history stack,因此您无法导航到历史堆栈上的当前位置。
查看它的文档
您可以使用history.push()incomponentWillReceiveProps函数以编程方式导航。
componentWillReceiveProps(nextProps) {
if(nextProps.itemsFetchSuccess !== this.props.itemsFetchSucess && nextProps.itemsFetchSuccess) {
this.props.history.push({
pathname: '/search',
search: `?item-name=${nextProps.searchQuery}`
})
}
}
Run Code Online (Sandbox Code Playgroud)
PS 确保您正在使用的组件history.push正在从连接的组件或使用 .Router 属性接收 Router 属性withRouter。检查此答案以获取有关如何使用 React-router 以编程方式导航的更多详细信息