首页 > 解决方案 > react-router throwing TypeError: useContext(...) is undefined when using useHistory

问题描述

在我自己的代码中,我尝试通过将 react-routeruseHistory添加到导入中来使用它:

import {BrowserRouter as Router, Link, Route, Switch, useHistory} from "react-router-dom";

然后在我的App()函数上用它定义一个变量:

let history = useHistory();

当我这样做时,我得到了错误:

TypeError: useContext(...) is undefined

来自 react-router 的hooks.js,具体线路是:

return useContext(Context).history;

整个文件如下所示:

import React from "react";
import invariant from "tiny-invariant";

import Context from "./RouterContext.js";
import matchPath from "./matchPath.js";

const useContext = React.useContext;

export function useHistory() {
  if (__DEV__) {
    invariant(
      typeof useContext === "function",
      "You must use React >= 16.8 in order to use useHistory()"
    );
  }

  return useContext(Context).history;
}

export function useLocation() {
  if (__DEV__) {
    invariant(
      typeof useContext === "function",
      "You must use React >= 16.8 in order to use useLocation()"
    );
  }

  return useContext(Context).location;
}

export function useParams() {
  if (__DEV__) {
    invariant(
      typeof useContext === "function",
      "You must use React >= 16.8 in order to use useParams()"
    );
  }

  const match = useContext(Context).match;
  return match ? match.params : {};
}

export function useRouteMatch(path) {
  if (__DEV__) {
    invariant(
      typeof useContext === "function",
      "You must use React >= 16.8 in order to use useRouteMatch()"
    );
  }

  return path
    ? matchPath(useLocation().pathname, path)
    : useContext(Context).match;
}

更多上下文:

在此处输入图像描述

我尝试访问React.useContext我自己的代码,它被定义并且它是一个函数。

有什么想法可能会在这里发生吗?

标签: reactjsreact-routerreact-hooks

解决方案


我认为您应该使用 BrowserRouter(作为路由器)将您的应用程序包装在 index.js 中,然后在您的应用程序中定义交换机和路由。因为您不能在使用 BrowserRouter 的同一文件中使用 useHistory 或 useLocation。所以,使用上一层的 BrowserRouter 包装器。


推荐阅读