React Router v7 已發布。 查看文件
unstable_usePrompt

unstable_usePrompt

unstable_usePrompt Hook 允許您在離開目前位置之前,透過 window.confirm 向使用者請求確認。

這僅適用於 React Router 應用程式內的客戶端導覽,並且不會阻止文件請求。要阻止文件導覽,您需要新增自己的 `beforeunload` 事件處理常式。 阻止使用者導覽有點反模式,因此請仔細考慮此 Hook 的任何使用方式,並謹慎使用。在防止使用者離開未填寫完畢的表單這個實際使用案例中,您可能會考慮將未儲存的狀態持久化到 `sessionStorage`,並在他們返回時自動重新填寫,而不是阻止他們離開。 我們不打算移除此 Hook 中的 `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>
  );
}
文件與範例授權採用 MIT