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
钩子允许您阻止用户离开当前位置,并向他们展示自定义 UI 以允许他们确认导航。
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
状态,并将用户留在当前位置。