React Router出现“无法读取未定义的属性位置”错误

问题描述

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

enter image description here

enter image description here

enter image description here

enter image description here

解决方法

仅当您在index.js中拥有它时,才需要“路由器”组件

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

从“ react-router-dom”导入{BrowserRouter as Router}

,

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

,

我相信路由器组件正在告诉我们开始监听位置。因此,在您的App.js中,首先将useLocation导入到您的react-router-dom中。然后使useEffect监听位置,以便路由器始终可以知道您所在的位置,从而确定要显示的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 ( ...
}