从重定向标记返回 - React Router [英] Going back from a redirect tag - React Router

查看:121
本文介绍了从重定向标记返回 - React Router的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我创建了一个搜索栏,我的搜索栏链接到我的搜索结果,如下所示:

Currently, I created a search bar and I have my search bar linked to my search results like this:

render() {
if (this.props.itemsFetchSuccess) {
  return (
    <Redirect to={{
      pathname: '/search',
      search: `?item-name=${this.props.searchQuery}`
    }} />
  );

作为搜索栏的渲染组件的一部分。

as part of the render component of my search bar.

GOOGLE CHROME MAIN - >主要着陆 - >搜索结果。

GOOGLE CHROME MAIN -> MAIN LANDING -> SEARCH RESULTS.

但我怀疑是因为我在React-Router v4中使用了重定向标记,它没有将它添加到浏览器历史堆栈中。如果我从搜索结果页面按回浏览器,它将不会返回到之前的页面(即主要着陆),但它将返回到主着陆之前的页面。

But I'm suspecting that because I used a redirect tag in React-Router v4, it's not adding it to the browser history stack. If I press back on a browser from the search results page, it won't go back to the page before (i.e. the main landing) but it'll go back to the page before the main landing.

有没有更好的方法来做到这一点,因为我尝试使用Link标签,但这不起作用,因为它只是生成链接而实际上并没有重定向一旦搜索结果完成。

Is there a better way of doing this as I tried using a Link tag as well but that doesn't work since it just generates the link and doesn't actually redirect once the search results are completed.

谢谢!

推荐答案

重定向会覆盖历史堆栈中的当前条目,因此您无法导航到历史堆栈中的当前位置。

Redirect overrides the current entry in history stack and hence you are not able to navigate to the current location on history stack.

查看 文档

See its documentation

您可以使用 history.push()以编程方式进行编程导航code> componentWillReceiveProps function。

You could instead programatically navigate using history.push() in componentWillReceiveProps function.

componentWillReceiveProps(nextProps) {
    if(nextProps.itemsFetchSuccess !== this.props.itemsFetchSucess && nextProps.itemsFetchSuccess) {
         this.props.history.push({
              pathname: '/search',
              search: `?item-name=${nextProps.searchQuery}`
         })
    }
}

PS确保您使用的组件 history.push 正在从连接的组件或使用 withRouter 。有关 如何使用React-router以编程方式导航的详细信息,请查看此答案

P.S. Make sure that the component in which you are using history.push is receiving the Router props, either from the connected component or using withRouter. Check this answer for more details on how to programmatically navigate using React-router

这篇关于从重定向标记返回 - React Router的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆