【问题标题】:Redux Toolkit - how to block navigation?Redux Toolkit - 如何阻止导航?
【发布时间】:2021-12-01 19:02:15
【问题描述】:

我不知道如何在 redux-toolkit 中实现 阻止页面导航。 例如,在切换到另一个页面之前,如果某个子句是false,则不允许切换。

如何做到这一点?

  • 我发现了一些可以通过react-router Prompt 完成的事情。
  • 另外,redux-toolkit 支持usePrefetch 钩子——但我不支持 确定它是否适用于此。
  • 还有history.push历史上的方法和东西 对象。

在切换到另一个页面之前,我需要检查队列中的对象数量。如果大于零,但不允许转到另一个页面。

我从未使用过阻止导航。 告诉我如何以最优化和最美观的方式专门为 Redux Toolkit 实现这一点?

【问题讨论】:

    标签: react-redux react-router redux-toolkit


    【解决方案1】:

    我在这里找到了解决方案

    Using history.block with asynchronous functions/callback/async/await

    const useIsValidBlockedPage = () => {
      const history = useHistory();
      const { isValid } = useFormikContext();
    
      useEffect(() => {
        const unblock = history.block(({ pathname }) => {
          // if is valid we can allow the navigation
          if (isValid) {
            // we can now unblock
            unblock();
            // proceed with the blocked navigation
            history.push(pathname);
          }
          // prevent navigation
          return false;
        });
    
        // just in case theres an unmount we can unblock if it exists
        return unblock;
      }, [isValid, history]);
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多