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

查看:32
本文介绍了从重定向标签返回 - 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 覆盖 history stack 中的当前条目,因此您无法导航到当前在历史堆栈中的位置.

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

您可以改为使用 componentWillReceiveProps 函数中的 history.push() 以编程方式导航.

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}`
         })
    }
}

附言确保您在其中使用 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天全站免登陆