【问题标题】:How to disable browser back button only for a specific component如何仅为特定组件禁用浏览器后退按钮
【发布时间】:2020-03-04 08:03:15
【问题描述】:

我有 3 个组件: 登录 仪表板 工作区

一旦用户成功登录,他将被导航到仪表板。从仪表板,他可以导航到工作区。 条件: 1.一旦登录导航到仪表板用户应该能够点击浏览器后退按钮返回登录页面。 2. 但他可以从工作区向后导航到仪表板

I have referred to this question to solve my problem

问题:条件 2 未达到。从仪表板导航到工作区后,我无法通过单击浏览器后退按钮导航回仪表板。

登录代码

login(newUser).then(res => { 

                if(res === "NULL")                        
                {
                    this.setState({confirmPswdShow: true});
                }else if(res === "wrongPassword")          
                {
                    const password ="password invalid";
                    this.setState({authPassword : password});
                }else{                                       
                   window.history.pushState(null, null, window.location.href);
                    window.onpopstate = function(event) {
                        window.history.go(1);
                    };              
                    this.props.history.push("/Dashboard");
                }
            })

仪表板代码

openProjectCreate(details){
        console.log(details);
        openProject(details)
        .then(res => {
            console.log(res);
            this.props.history.push("/WorkSpace");
        })
    }

【问题讨论】:

  • 您导航到仪表板,然后单击某些内容导航到工作区,然后单击后退按钮返回仪表板不起作用?你能给我们看一些代码吗?
  • 是的,我会添加代码
  • 是的.....从工作区,我应该能够在浏览器后退按钮的帮助下导航回仪表板
  • 为什么要加这个? window.onpopstate = function(event) { window.history.go(1); };
  • 这样在点击浏览器后退按钮时不会出现上一页

标签: reactjs react-router


【解决方案1】:

您不应该覆盖窗口上的弹出功能。要禁用返回登录,只需在历史记录中替换它的 URL:

login(newUser).then(res => {
    if (res === "NULL") {
        this.setState({
            confirmPswdShow: true
        });
    } else if (res === "wrongPassword") {
        const password = "password invalid";
        this.setState({
            authPassword: password
        });
    } else {
        this.props.history.replace({
            pathname: '/Dashboard'
        });
        this.props.history.push("/Dashboard");
    }
})

【讨论】:

    猜你喜欢
    • 2011-08-06
    • 2010-10-31
    • 2014-04-17
    • 2014-05-08
    • 2020-08-17
    • 2014-08-21
    • 2018-01-14
    相关资源
    最近更新 更多