"Cannot Read Property Location of Undefined" React 路由器出错

"Cannot Read Property Location of Undefined" Error with React Router

我正在开发一个简单的 React 店面,但我的路由器设置存在一个错误。我提供了相关文件的屏幕截图和错误消息。路由器的文件流为 Navbar.js -> App.js -> Index.js。我已经很长时间没有做任何路由了,所以如果有遗漏的细节或我没有正确解释的事情,我深表歉意。任何建议都会有所帮助。

“路由器”组件只需要一次,就像在 index.js

中一样

Navbar.js 不需要“路由器”组件,因此您可以将其删除。此外,您在 Navbar.js 中导入的“路由器”是错误的(在 index.js 中是正确的)

从“react-router-dom”导入 { BrowserRouter 作为路由器}“

您需要在 React class 组件中使用 this.propsthis.props.history.location

我相信路由器组件告诉我们开始侦听位置。因此,在您的 App.js 中,首先将 useLocation 导入到您的 react-router-dom 中。然后让 useEffect 监听位置,这样 Router 总能知道你在哪个位置,从而确定要显示哪个 Route 组件。

示例:

import { useLocation } from 'react-router-dom';

function App() {
  const location = useLocation();
  useEffect(() => {
    const currentPath = location.pathname;
    const searchParams = new URLSearchParams(location.search);
  }, [location]);
  return ( ...
}