unstable_usePrompt

unstable_usePrompt

unstable_usePrompt 钩子允许你在用户离开当前位置之前通过 window.confirm 提示用户确认。

¥The unstable_usePrompt hook allows you to prompt the user for confirmation via window.confirm prior to navigating away from the current location.

这仅适用于 React Router 应用中的客户端导航,并且不会阻止文档请求。要阻止文档导航,你需要添加自己的 beforeunload 事件处理程序。

阻止用户导航有点像反模式,所以请仔细考虑这个钩子的任何用法,并谨慎使用。在阻止用户离开半填写表单的实际用例中,你可以考虑将未保存的状态持久化到 sessionStorage,并在用户返回时自动重新填写,而不是阻止他们离开。

我们不打算从这个钩子中删除 unstable_ 前缀,因为在提示符打开时,跨浏览器的行为是不确定的,因此 React Router 无法保证在所有情况下都正确运行。为了避免这种不确定性,我们建议使用 useBlocker,它也能让你控制确认用户体验。

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>
  );
}
Remix v2.17 中文网 - 粤ICP备13048890号