useBlocker
On this page

useBlocker

useBlocker 钩子允许你阻止用户离开当前位置,并向他们渲染一个自定义 UI,以便他们确认导航。

¥The useBlocker hook allows you to prevent the user from navigating away from the current location, and present them with a custom UI to allow them to confirm the navigation.

这仅适用于 React Router 应用中的客户端导航,并且不会阻止文档请求。要阻止文档导航,你需要添加自己的 beforeunload 事件处理程序。

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

function ImportantForm() {
  const [value, setValue] = React.useState("");

  // Block navigating elsewhere when data has been entered into the input
  const 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>
  );
}

有关更完整的示例,请参阅代码库中的 example

¥For a more complete example, please refer to the example in the repository.

属性

¥Properties

state

拦截器的当前状态

¥The current state of the blocker

  • unblocked - 拦截器处于空闲状态,未阻止任何导航

    ¥unblocked - the blocker is idle and has not prevented any navigation

  • blocked - 拦截器阻止了导航

    ¥blocked - the blocker has prevented a navigation

  • proceeding - 拦截器正在从被阻止的导航继续执行

    ¥proceeding - the blocker is proceeding through from a blocked navigation

location

当处于 blocked 状态时,这表示我们阻止导航到的位置。当处于 proceeding 状态时,这是调用 blocker.proceed() 后导航到的位置。

¥When in a blocked state, this represents the location to which we blocked a navigation. When in a proceeding state, this is the location being navigated to after a blocker.proceed() call.

方法

¥Methods

proceed()

当处于 blocked 状态时,你可以调用 blocker.proceed() 继续前往被阻止的位置。

¥When in a blocked state, you may call blocker.proceed() to proceed to the blocked location.

reset()

当处于 blocked 状态时,你可以调用 blocker.reset() 将阻止程序返回到 unblocked 状态,并将用户留在当前位置。

¥When in a blocked state, you may call blocker.reset() to return the blocker to an unblocked state and leave the user at the current location.

Remix v2.17 中文网 - 粤ICP备13048890号