unstable_usePrompt
このコンテンツはまだ日本語訳がありません。
unstable_usePrompt
unstable_usePrompt
钩子允许你在离开当前位置之前通过 window.confirm
提示用户确认。
这仅适用于 React Router 应用程序内的客户端导航,不会阻止文档请求。要阻止文档导航,您需要添加自己的 beforeunload
事件处理程序。
阻止用户导航有点反模式,因此请仔细考虑此钩子的任何用法并谨慎使用。在防止用户离开半填表单的实际用例中,您可以考虑将未保存的状态保留到sessionStorage
,并在他们返回时自动重新填充,而不是阻止他们离开。
我们不打算从此钩子中删除 unstable_
前缀,因为当提示打开时,跨浏览器的行为是不确定的,因此 React Router 无法保证在所有情况下都正确无误。为了避免这种不确定性,我们建议改用 useBlocker
,它还可以让您控制确认 UX。
function ImportantForm() { const [value, setValue] = React.useState("");
// Block navigating elsewhere when data has been entered into the input unstable_usePrompt({ message: "Are you sure?", when: ({ 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> </Form> );}