te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Getting navigator.block is not a function while navigating to other page - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting navigator.block is not a function while navigating to other page - Stack Overflow

programmeradmin2浏览0评论

In a React project, I've created a popup modal which will be displayed when any user tries to do any changes in input field and navigate to other screen. It doesn't work as expected, hence gone through many posts to find the solution but, no luck. Please refer to code below:

useBlock.js

import {useContext, useEffect} from 'react';
import { UNSAFE_NavigationContext as NavigationContext} from 'react-router-dom';
const useBlocker = (blocker, when = true) => {
    const navigator = useContext(NavigationContext).navigator
    useEffect(() => {
        if (!when)
            return;
        const unblock = navigator.block((tx) => { <-- This line is creating an issue
            const autoUnblockingTx = {
                ...tx,
                retry() {
                  unblock();
                  tx.retry();
                },
              };
            blocker(autoUnblockingTx);
        });
        return unblock;
    }, [navigator, blocker, when]);
}

export default useBlocker

useCallbackPrompt.js

import { useCallback, useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router';
import useBlocker from './useBlocker';

const useCallbackPrompt = (when) => {
    const navigate = useNavigate();
    const location = useLocation();
    const [showPrompt, setShowPrompt] = useState(false);
    const [lastLocation, setLastLocation] = useState(null);
    const [confirmedNavigation, setConfirmedNavigation] = useState(false);
    const cancelNavigation = useCallback(() => {
        setShowPrompt(false);
    }, []);

    const handleBlockedNavigation = useCallback((nextLocation) => {
        if (!confirmedNavigation &&
            nextLocation.location.pathname !== location.pathname) {
            setShowPrompt(true);
            setLastLocation(nextLocation);
            return false;
        }
        return true;
    }, [confirmedNavigation]);
    
    const confirmNavigation = useCallback(() => {
        setShowPrompt(false);
        setConfirmedNavigation(true);
    }, []);
    useEffect(() => {
        if (confirmedNavigation && lastLocation) {
            navigate(lastLocation.location.pathname);
        }
    }, [confirmedNavigation, lastLocation]);
    useBlocker(handleBlockedNavigation, when);
    return [showPrompt, confirmNavigation, cancelNavigation];
}

export default useCallbackPrompt

So above are the 2 files which I'm using. In useBlocker.js file that particular line is actually causing the root issue. Please refer to the image below

I'm using "react-router-dom": "^6.3.0", Is this causing any issue? Any suggestions or modifications are highly appreciated.

In a React project, I've created a popup modal which will be displayed when any user tries to do any changes in input field and navigate to other screen. It doesn't work as expected, hence gone through many posts to find the solution but, no luck. Please refer to code below:

useBlock.js

import {useContext, useEffect} from 'react';
import { UNSAFE_NavigationContext as NavigationContext} from 'react-router-dom';
const useBlocker = (blocker, when = true) => {
    const navigator = useContext(NavigationContext).navigator
    useEffect(() => {
        if (!when)
            return;
        const unblock = navigator.block((tx) => { <-- This line is creating an issue
            const autoUnblockingTx = {
                ...tx,
                retry() {
                  unblock();
                  tx.retry();
                },
              };
            blocker(autoUnblockingTx);
        });
        return unblock;
    }, [navigator, blocker, when]);
}

export default useBlocker

useCallbackPrompt.js

import { useCallback, useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router';
import useBlocker from './useBlocker';

const useCallbackPrompt = (when) => {
    const navigate = useNavigate();
    const location = useLocation();
    const [showPrompt, setShowPrompt] = useState(false);
    const [lastLocation, setLastLocation] = useState(null);
    const [confirmedNavigation, setConfirmedNavigation] = useState(false);
    const cancelNavigation = useCallback(() => {
        setShowPrompt(false);
    }, []);

    const handleBlockedNavigation = useCallback((nextLocation) => {
        if (!confirmedNavigation &&
            nextLocation.location.pathname !== location.pathname) {
            setShowPrompt(true);
            setLastLocation(nextLocation);
            return false;
        }
        return true;
    }, [confirmedNavigation]);
    
    const confirmNavigation = useCallback(() => {
        setShowPrompt(false);
        setConfirmedNavigation(true);
    }, []);
    useEffect(() => {
        if (confirmedNavigation && lastLocation) {
            navigate(lastLocation.location.pathname);
        }
    }, [confirmedNavigation, lastLocation]);
    useBlocker(handleBlockedNavigation, when);
    return [showPrompt, confirmNavigation, cancelNavigation];
}

export default useCallbackPrompt

So above are the 2 files which I'm using. In useBlocker.js file that particular line is actually causing the root issue. Please refer to the image below

I'm using "react-router-dom": "^6.3.0", Is this causing any issue? Any suggestions or modifications are highly appreciated.

Share Improve this question asked Oct 18, 2022 at 6:28 Prakash PatilPrakash Patil 2771 gold badge3 silver badges12 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 7

I wasn't able to reproduce the issue using [email protected], but I could when bumping to [email protected]. I suspect with a dependency specified as ^6.3.0 you've actually a more current version actually installed. If you like you can check the installed version by running npm list react-router-dom and verify for yourself.

It seems the navigation context has a mildly breaking change between v6.3.0 and v6.4.0. The v6.3.0 version is a history object (source) while the v6.4.0 is a new navigation context object where navigator is a simpler interface (source).

Solution 1 - Revert to previous version

You could revert back to 6.3.0 though by running npm i -s [email protected] to install that exact version. Double-check your package.json file to ensure the entry is "react-router-dom": "6.3.0".

Solution 2 - Use the "real" history object

If you wanted to move forward with the newer RRD versions then an alternative I'd suggest is to use the history@5 history object directly instead of trying to use the react-router@6 navigator. RRDv6 was only ever exporting a subset of the history methods anyway.

  1. Add history@5 as a project dependency.

    IMPORTANT: You will want to check what version react-router-dom is using and match if you can.

  2. Create and export a custom history object. createBrowserHistory for a BrowserRouter, createHashHistory for a HashRouter, etc.

    import { createBrowserHistory } from 'history';
    
    const history = createBrowserHistory();
    
    export default history;
    
  3. Import your custom history object and the history router from RRD.

    import { unstable_HistoryRouter as Router } from "react-router-dom";
    import history from './history';
    
    ...
    
    <Router history={history}>
      <App />
    </Router>
    
  4. Import your custom history object to use in your custom hooks.

    import { useCallback, useEffect, useState } from "react";
    import { useNavigate, useLocation } from "react-router-dom";
    import history from "./history"; // <-- import
    
    const useBlocker = (blocker, when = true) => {
      useEffect(() => {
        if (!when) return;
        const unblock = history.block((tx) => { // <-- use history
          const autoUnblockingTx = {
            ...tx,
            retry() {
              unblock();
              tx.retry();
            }
          };
          blocker(autoUnblockingTx);
        });
        return unblock;
      }, [blocker, when]);
    };
    

    useCallbackPrompt is untouched.

    const useCallbackPrompt = (when) => {
      const navigate = useNavigate();
      const location = useLocation();
      const [showPrompt, setShowPrompt] = useState(false);
      const [lastLocation, setLastLocation] = useState(null);
      const [confirmedNavigation, setConfirmedNavigation] = useState(false);
      const cancelNavigation = useCallback(() => {
        setShowPrompt(false);
      }, []);
    
      const handleBlockedNavigation = useCallback(
        (nextLocation) => {
          if (
            !confirmedNavigation &&
            nextLocation.location.pathname !== location.pathname
          ) {
            setShowPrompt(true);
            setLastLocation(nextLocation);
            return false;
          }
          return true;
        },
        [confirmedNavigation]
      );
    
      const confirmNavigation = useCallback(() => {
        setShowPrompt(false);
        setConfirmedNavigation(true);
      }, []);
      useEffect(() => {
        if (confirmedNavigation && lastLocation) {
          navigate(lastLocation.location.pathname);
        }
      }, [confirmedNavigation, lastLocation]);
      useBlocker(handleBlockedNavigation, when);
      return [showPrompt, confirmNavigation, cancelNavigation];
    };
    

Demo

From v6.4.0 navigator.block is removed. You can find a workaround here: https://gist.github./MarksCode/64e438c82b0b2a1161e01c88ca0d0355.

Also, relevant discussion going on here. https://github./remix-run/react-router/issues/8139#issuement-1262630360

In v6.7.0 they added unstable_useBlocker and unstable_usePrompt and those are still there.

So you can either use unstable_usePrompt directly or if you want some custom ponent to be shown you can try to bine your custom solution with unstable_useBlocker.

I did this in my case:

export function usePrompt(when = true) {
  const blocker = unstable_useBlocker(when);

  useEffect(() => {
    // message in latest Chrome will be ignored anyway - it uses its own
    if (when) window.onbeforeunload = () => "Are you sure?";

    return () => {
      window.onbeforeunload = null;
    };
  }, [when]);

  useEffect(() => {
    if (blocker.state === "blocked") {
      const element = document.createElement("div");
      element.setAttribute("id", "prompt-dialog-container");
      element.setAttribute("aria-hidden", "true");

      const closePrompt = (state: boolean) => {
        if (element) {
          ReactDOM.unmountComponentAtNode(element);
        }
        if (!state) {
          document.body.removeChild(element);
          blocker.reset();
        } else {
          blocker.proceed();
        }
      };

      document.body.appendChild(element);
      // just a modal with message "You have unsaved changes in this report. Do you want to save your changes?" and 2 buttons [Yes] and [No]
      ReactDOM.render(<ExitPrompt onYes={() => closePrompt(false)} onNo={() => closePrompt(true)} />, element);
    }
  }, [blocker]);
}
发布评论

评论列表(0)

  1. 暂无评论