Intercept/handle browser's back button in React-router?

前端 未结 12 1100
滥情空心
滥情空心 2020-11-27 03:47

I\'m using Material-ui\'s Tabs, which are controlled and I\'m using them for (React-router) Links like this:

    

        
12条回答
  •  清歌不尽
    2020-11-27 04:32

    Most of the answers for this question either use outdated versions of React Router, rely on less-modern Class Components, or are confusing; and none use Typescript, which is a common combination. Here is an answer using Router v5, function components, and Typescript:

    // use destructuring to access the history property of the ReactComponentProps type
    function MyComponent( { history }: ReactComponentProps) {
    
        // use useEffect to access lifecycle methods, as componentDidMount etc. are not available on function components.
        useEffect(() => {
    
            return () => {
                if (history.action === "POP") {
                    // Code here will run when back button fires. Note that it's after the `return` for useEffect's callback; code before the return will fire after the page mounts, code after when it is about to unmount.
                    }
               }
        })
    }
    

    A fuller example with explanations can be found here.

提交回复
热议问题