useBlocker
declare function useBlocker(
shouldBlock: boolean | BlockerFunction
): Blocker;
type BlockerFunction = (args: {
currentLocation: Location;
nextLocation: Location;
historyAction: HistoryAction;
}) => boolean;
type Blocker =
| {
state: "unblocked";
reset: undefined;
proceed: undefined;
location: undefined;
}
| {
state: "blocked";
reset(): void;
proceed(): void;
location: Location;
}
| {
state: "proceeding";
reset: undefined;
proceed: undefined;
location: Location;
};
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",
}
useBlocker
鉤子函式能讓您在使用者離開目前位置前加以阻止,並顯示自訂使用者介面,請求他們確認是否要離開。
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>
);
}
若要取得更完整的範例,請參閱儲存庫中的 範例。
state
攔截器的當前狀態
unblocked
- 攔截器處於閒置狀態,尚未阻止任何導覽blocked
- 攔截器已阻止導覽proceeding
- 封鎖器正從被封鎖的導覽中進行location
在 blocked
狀態時,此值代表我們封鎖導覽的位置。在 proceeding
狀態時,此值是 blocker.proceed()
呼叫後導向到的位置。
proceed()
在 blocked
狀態時,您可以呼叫 blocker.proceed()
來前往被封鎖的位置。
reset()
在 blocked
狀態時,您可以呼叫 blocker.reset()
來使封鎖器回到 unblocked
狀態,並停留在目前的瀏覽位置。