从重定向标签返回 - React Router

5

目前,我创建了一个搜索栏,并且将其与搜索结果链接在一起,就像这样:

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

作为我的搜索栏渲染组件的一部分。
谷歌Chrome主要页面 -> 主要落地页 -> 搜索结果页面。
但我怀疑是因为我在React-Router v4中使用了重定向标签,它没有将其添加到浏览器历史记录堆栈中。如果我从搜索结果页面在浏览器上按返回键,它不会返回到之前的页面(即主要落地页),而是会返回到主要落地页之前的页面。
是否有更好的方法来解决这个问题?我也尝试过使用Link标签,但那不起作用,因为它只生成链接,并不会在搜索完成后实际重定向。
谢谢!

我不确定我是否理解得足够清楚,但也许 window.location.href 就是答案了? - TamirNahum
我的意思是,当我点击搜索栏后,它会发出redux调用以请求来自我的API的数据,因此在完成时加载。但是,由于我需要路由保持相同的“路径名、搜索字段”,我正在尝试找到另一种方法来避免使用重定向标签。 - Somnium
3个回答

7
在您的情况下,您可以使用带有“push”参数的重定向。当按下返回按钮时,它将正确地重定向到先前的页面。
* push:bool
如果为true,则重定向将向历史记录中添加一个新条目,而不是替换当前条目。
<Redirect push to={{
    pathname: '/search',
    search: `?item-name=${this.props.searchQuery}`
}} />

我已经与React Router这个问题斗争了几周,而这正是我需要做的。它让我发疯了。谢谢你! - maison.m

1

试试这个:

this.props.history.push(`/search?item-name=${this.props.searchQuery}`);

1

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

请参阅其 文档

您可以改为在 componentWillReceiveProps 函数中使用 history.push() 进行编程导航。

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

注意,在使用 history.push 的组件中,需要接收来自连接的组件或使用 withRouter 传递的 Router props。请参阅 如何使用 React-router 进行编程导航的更多细节


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接