gpt4 book ai didi

javascript - 我想在 Next.js 中的路由更改之前创建一个确认模式

转载 作者:行者123 更新时间:2023-12-05 05:39:43 26 4
gpt4 key购买 nike

我有这样的代码块

const onRouteChangeStart = React.useCallback(() => {
if (formState.isDirty) {
if (window.confirm('Confirmation message')) {
return true;
}
NProgress.done();
throw "Abort route change by user's confirmation.";
}
}, [formState.isDirty]);

React.useEffect(() => {
Router.events.on('routeChangeStart', onRouteChangeStart);

return () => {
Router.events.off('routeChangeStart', onRouteChangeStart);
};
}, [onRouteChangeStart]);

它按我的意愿工作,但我想添加一个自定义确认模式而不是 native 确认

当我添加时,路线变化并没有停止。这就是我等不及用户响应的原因。

我能做什么?感谢您的回复。

最佳答案

这里有一个很好的示例,它中止当前的路由更改并将其保存到状态,提示自定义模型。如果确认,它会再次推送路由。

https://github.com/vercel/next.js/discussions/32231?sort=new?sort=new#discussioncomment-2033546

import { useRouter } from 'next/router';
import React from 'react';
import Dialog from './Dialog';

export interface UnsavedChangesDialogProps {
shouldConfirmLeave: boolean;
}

export const UnsavedChangesDialog = ({
shouldConfirmLeave,
}: UnsavedChangesDialogProps): React.ReactElement<UnsavedChangesDialogProps> => {
const [shouldShowLeaveConfirmDialog, setShouldShowLeaveConfirmDialog] = React.useState(false);
const [nextRouterPath, setNextRouterPath] = React.useState<string>();

const Router = useRouter();

const onRouteChangeStart = React.useCallback(
(nextPath: string) => {
if (!shouldConfirmLeave) {
return;
}

setShouldShowLeaveConfirmDialog(true);
setNextRouterPath(nextPath);

throw 'cancelRouteChange';
},
[shouldConfirmLeave]
);

const onRejectRouteChange = () => {
setNextRouterPath(null);
setShouldShowLeaveConfirmDialog(false);
};

const onConfirmRouteChange = () => {
setShouldShowLeaveConfirmDialog(false);
// simply remove the listener here so that it doesn't get triggered when we push the new route.
// This assumes that the component will be removed anyway as the route changes
removeListener();
Router.push(nextRouterPath);
};

const removeListener = () => {
Router.events.off('routeChangeStart', onRouteChangeStart);
};

React.useEffect(() => {
Router.events.on('routeChangeStart', onRouteChangeStart);

return removeListener;
}, [onRouteChangeStart]);

return (
<Dialog
title="You have unsaved changes"
description="Leaving this page will discard unsaved changes. Are you sure?"
confirmLabel="Discard changes"
cancelLabel="Go back"
isOpen={shouldShowLeaveConfirmDialog}
onConfirm={onConfirmRouteChange}
onReject={onRejectRouteChange}
/>
);
};

关于javascript - 我想在 Next.js 中的路由更改之前创建一个确认模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72617268/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com