main
分支
main (6.23.1)dev
版本
6.23.1v4/5.xv3.x
unstable_usePrompt

unstable_usePrompt

類型宣告
declare function unstable_usePrompt({
  when,
  message,
}: {
  when: boolean | BlockerFunction;
  message: string;
}) {

type BlockerFunction = (args: {
  currentLocation: Location;
  nextLocation: Location;
  historyAction: HistoryAction;
}) => boolean;

interface Location<State = any> extends Path {
  state: State;
  key: string;
}

interface Path {
  pathname: string;
  search: string;
  hash: string;
}

enum HistoryAction {
  Pop = "POP",
  Push = "PUSH",
  Replace = "REPLACE",
}

unstable_usePrompt 掛鉤允許您在從目前位置導航離開之前,透過 window.confirm 詢問使用者確認。

這僅適用於 React Router 應用程式內的用戶端導航,且不會阻擋文件請求。若要防止文件導航,您需要新增自己的 `beforeunload` 事件處理常式。 阻擋使用者導航有點違背模式,因此請仔細考慮這個掛鉤的任何用法,並謹慎使用。在阻止使用者離開半填寫的表單的實際使用案例中,您可以考慮將未儲存的狀態持續到 `sessionStorage`,如果他們回來,自動再次填寫,而不是阻擋他們離開。 我們不打算從這個掛鉤中移除 `unstable_` 前置詞,因為當提示開啟時,行為在所有瀏覽器中是非確定性的,因此 React Router 無法保證在所有情況下都能正確執行。若要避免這種不確定性,我們建議使用 `useBlocker`,它也能讓您控制確認 UX。
function ImportantForm() {
  let [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>
  );
}
文件和範例 CC 4.0