useBlocker

通过useBlocker钩子,可以阻止用户从当前位置导航出去,并向他们显示一个自定义UI,以允许他们确认导航。

这仅适用于React路由器应用程序中的客户端导航,不会阻止文档请求。要防止文档导航,您需要添加自己的“beforeunload”事件处理程序。

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

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>
  );
}

最后更新于

这有帮助吗?