我在让useHistory()
挂钩在我的应用程序中工作时遇到了一个问题。它在<Route>
的顶级子级中起作用,但在该顶级子级所包含的任何组件中都不起作用。
用代码解释得更好。
在框架容器中:
const { path } = useRouteMatch();
<Switch>
<Route path={`${path}/reading`} exact>
<Reading />
</Route>
</Switch>
在Reading
组件中:
export default function Reading(props) {
const history = useHistory();
// history is correct here and contains the pop(), push(), etc.
return (
<>
<Navbar />
</>
);
}
在Navbar
组件中:
export default function Navbar(props) {
let history = useHistory();
// history is undefined here - WHY??
return (
// navbar JSX code here
);
}
为什么useHistory()
不能在Navbar
组件中工作?在我看来,只有顶级儿童才能使用这个钩子是不对的,它应该可以从链条上取下来,对吧?
useHistory
在不在Route
内部的组件中不起作用。因此,在导航栏组件中使用withRouter
。
import {withRouter} from "react-router-dom";
const Navbar=(props)=> {
let history = useHistory();
// history is undefined here - WHY??
return (
// navbar JSX code here
);
}
export default withRouter(Navbar)
我想明白了,希望这能帮助其他人。我的项目使用了/app文件夹和/common文件夹,每个文件夹都有自己的package.json文件。导航栏在/common中,其他文件在/app中。
react router dom所做的是将历史信息存储在/nod_module文件夹中自己的文件中,而不是react应用程序中的任何位置。因此,由于我有两个package.json文件,我有两个子文件夹/node_modules,因此Navbar正在寻找一个不存在的历史记录,因为它在另一个/node_modeles文件夹中。