ReactRouter v4 Prompt - override default alert

前端 未结 3 961
抹茶落季
抹茶落季 2020-12-20 15:09

The React Router v4 component is perfect for the use case of protecting navigation away from a partially filled out form.

3条回答
  •  情深已故
    2020-12-20 15:54

    Here's a component using hooks to achieve block functionality, the component didn't work for me because I wanted to ignore the search on the location.

    import { useEffect, useRef } from 'react';
    import { useHistory } from 'react-router-dom';
    
    interface IProps {
        when: boolean;
        message: string;
    }
    
    export default function RouteLeavingGuard({ when, message }: IProps) {
    
        const history = useHistory();
        const lastPathName = useRef(history.location.pathname);
    
        useEffect(() => {
    
            const unlisten = history.listen(({ pathname }) => lastPathName.current = pathname);
    
            const unblock = history.block(({ pathname }) => {
                if (lastPathName.current !== pathname && when) {
                    return message;
                }
            });
    
            return () => {
                unlisten();
                unblock();
            }
        }, [history, when, message]);
    
        return null;
    
    }
    

提交回复
热议问题