封装hook
import { useEffect, useRef } from 'react';
import { Prompt, useHistory, useLocation } from 'react-router-dom';
export default function useWindowBeforeUnload(getMessage: () => string | undefined) {
const location = useLocation();
const history = useHistory();
const ref = useRef({
pathname: location.pathname,
}).current;
useEffect(() => {
const promptBeforeUnload = (event: BeforeUnloadEvent) => {
const message = getMessage();
console.log('message before unload', message);
if (!message) return;
event.preventDefault();
event.returnValue = message;
return message;
};
window.addEventListener('beforeunload', promptBeforeUnload);
return () => window.removeEventListener('beforeunload', promptBeforeUnload);
});
const renderPrompt = () => (
<Prompt
when={!!getMessage()}
message={(location, action) => {
const message = getMessage();
if (message) return `${message}(即将跳转:${location.pathname}${location.search})`;
return false;
}}
/>
);
return { renderPrompt };
}
使用hook
import useWindowBeforeUnload from '@/hooks/useWindowBeforeUnload';
export default function () {
const { renderPrompt } = useWindowBeforeUnload(() => {
return '如果有未保存的修改,离开后将会丢失!';
});
return (
<div>
{renderPrompt()}
</div>
);
}