reactjs - 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
我自己的代码,它被定义并且它是一个函数。
有什么想法可能会在这里发生吗?
解决方案
我认为您应该使用 BrowserRouter(作为路由器)将您的应用程序包装在 index.js 中,然后在您的应用程序中定义交换机和路由。因为您不能在使用 BrowserRouter 的同一文件中使用 useHistory 或 useLocation。所以,使用上一层的 BrowserRouter 包装器。
推荐阅读
- python - 无法将“\”替换为“/”
- flutter - 如何测量颤振性能和渲染时间
- haskell - Haskell函数递归删除列表中给定值的所有出现
- php - PHP - 读取 CSV 文件并将列连接到分隔行并输出到新文件中
- reactjs - 如何通过在反应多选中选择一个选项来替换 Select ...?
- javascript - VoiceOver 不解析 React SPA 中的 DOM?
- docker - Docker 错误:没有这样的容器:路径 .. 尝试复制到本地驱动器时
- r - rjdbc dbSendUpdate ORA-12899 值对于列来说太大
- python - 使用 JSON 的原子 Redis 操作
- r - 任何人都可以帮我解释我在将 tensorflow 用于神经网络时获得的这些图表吗?