开发者问题收集

React Router 错误:无法读取未定义的属性(读取‘路径名’)

2022-08-28
4333

我试图将导航栏添加到 Webb 应用程序,当我将 <Navbar/> 放入 App.js 时,我收到以下错误。我了解到该错误可能与 <Link/>to 属性有关,但我找不到任何问题,而且我无法理解此错误。我很感激所有的想法,感谢您的时间!

> components.tsx:197 Uncaught TypeError: Cannot read properties of undefined (reading 'pathname')
    at Router (components.tsx:197:1)

react-dom.development.js:18687 The above error occurred in the component: at Router (http://localhost:3003/static/js/bundle.js:62004:15) at App

Consider adding an error boundary to your tree to customize error handling behavior. Visit https://reactjs.org/link/error-boundaries to learn

导航栏:

export default function Navbar() {
  return (
    <nav className="nav">
      <Link to="/" className="site-title">
        
      </Link>
      <ul>
        <CustomLink to="/reflect">Reflect</CustomLink>
        <CustomLink to="/edi">Edi</CustomLink>
      </ul>
    </nav>
  )
}
  function CustomLink({ to, children, ...props }) {
  const resolvedPath = useResolvedPath(to)
  const isActive = useMatch({ path: resolvedPath.pathname, end: true })
  return (
    <li className={isActive ? "active" : ""}>
      <Link to={to} {...props}>
        {children}
      </Link>
    </li>
  )
}

App.js:

function App() {
  return (
    <>
      <Router>
        <NavBar />
        <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/reflect" element={<Reflect />} />
        <Route path="/edi" element={<Edi />} />
        <Route path="/storyboard" element={<StoryBoard />} />
        <Route path="/texteditor" element={<TextEditor />} />
        <Route path="/*" element={<errorPage />} />
        </Routes>    
      </Router>
       </>
  );
}
export default App;
  
1个回答

您不应使用 <Router> 。这需要您实例化并传入自己的 history <Router history={history}> 。请改用 BrowserRouter

Chase
2022-08-29