【问题标题】:Can you go backwards through react-router v4 hashHistory?你能通过 react-router v4 hashHistory 倒退吗?
【发布时间】:2025-12-23 20:20:26
【问题描述】:

想知道如何在 react-router v4 中使用 hashRouter 而不是 browserRouter 在 React Web 应用程序中返回上一个路由?

我发现this 问题似乎不起作用,即使它说不需要浏览器混合(另外我认为它谈论的是较旧的 react-router 版本)但是,我见过的所有其他解决方案都取决于在浏览器历史上。

hashHistory 可以吗?

【问题讨论】:

    标签: reactjs react-router-v4 html5-history


    【解决方案1】:

    好吧,就我而言,我确实喜欢这样:

    import withRouter from "react-router-dom/es/withRouter";
    import React from "react";
    
    class Component extends React.Component {
      goBack() {
        this.props.history.go(-1);
      }
      ...
    }    
    const WrappedComponent = withRouter(Component)
    export default WrappedComponent;
    

    withRouter 让我们可以访问组件 props 中的历史记录,但我不确定这种方式是否正确

    【讨论】:

    • 它不起作用。失败并显示错误消息:组件不是变量。
    • 是的,确实是因为我的名字弄错了:)
    【解决方案2】:
    this.props.history.goBack()
    

    取自this question的cmets

    这是一个函数调用。

    【讨论】:

    • 我在我的主页 this.props.history.push({ pathname: '/Classlist'}) 和 this.props.history.goBack() 中使用了这个到 Classlist 页面它工作得很好但是当这个.props.history.push({ pathname: '/classdetail'}) 当我使用 this.props.history.goBack() 进入classdetail页面时,它被重定向到'/'的确切路径