阻止用户导航有点反模式,所以请仔细考虑这个钩子的任何用法,并谨慎使用它。在防止用户从半填充的表单中导航离开的实际用例中,您可能会考虑将未保存的状态保存到“sessionStorage”,并在他们返回时自动重新填充它,而不是阻止他们导航离开。
function ImportantForm() {
let [value, setValue] = React.useState("");
// Block navigating elsewhere when data has been entered into the input
let blocker = useBlocker(
({ currentLocation, nextLocation }) =>
value !== "" &&
currentLocation.pathname !== nextLocation.pathname
);
return (
<Form method="post">
<label>
Enter some important data:
<input
name="data"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
</label>
<button type="submit">Save</button>
{blocker.state === "blocked" ? (
<div>
<p>Are you sure you want to leave?</p>
<button onClick={() => blocker.proceed()}>
Proceed
</button>
<button onClick={() => blocker.reset()}>
Cancel
</button>
</div>
) : null}
</Form>
);
}