React Router Dom v4处理浏览器后退按钮 [英] React Router Dom v4 handle browser back button

查看:437
本文介绍了React Router Dom v4处理浏览器后退按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用react-router-dom v4禁止用户点击浏览器后退按钮?

How do I disable a browser back button click from user using react-router-dom v4?

我正在页面上显示一个模式,当用户按下浏览器后退按钮时,用户将转到上一个屏幕,而我只是想关闭模式.

I am showing a modal on a page and when the user presses browser back button then the user is taken to the previous screen, instead I want to simply close the modal.

我尝试这样做

onBackButtonEvent(event) {
    event.preventDefault();  
    // the user shouldn't be able to move backward or forward  
}
componentDidMount() {
    window.onpopstate = this.onBackButtonEvent;
}

但这不会阻止用户后退或前进.有没有办法通过react-router-dom处理此问题?

But this doesn't prevent the user from going backward or forward. Is there a way to handle this via react-router-dom?

我尝试了多种解决方案,但似乎无济于事.

I have tried multiple solutions but nothing seems to work.

推荐答案

我知道这个问题有点老了,但是我自己寻找答案时偶然发现了这个问题.没有清除"后退按钮的干净方法,而是让用户仅在单击浏览器后退按钮时关闭模式,我发现这是可行的.

I know this question's a little old but I stumbled on it while looking for the answer myself. There's no clean way to "disable" the back button but to enable the user to only close the modal when clicking the browser back button I found this to work.

只需将历史记录传递到props中的模态组件,然后在componentWillUnmount函数中调用以下内容即可.

Simply pass the history to your modal component in props and call the below on the componentWillUnmount function.

componentWillUnmount() {
    this.props.history.goForward();
}

这将无缝地迫使浏览器停留在同一页面上,但关闭模式(假设它是一个类组件).

This will seamlessly force the browser to stay on the same page but close the modal (assuming it's a class component).

更新:如果使用功能组件,则上面的内容看起来像下面的钩子

UPDATE: If using functional components, the above looks like the hook below

React.useEffect(() => {
    return () => {
            props.history.goForward();
        }
    }
}, []);

这篇关于React Router Dom v4处理浏览器后退按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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