reactjs 未捕获的类型错误:无法解构“React2”的属性“basename”,useContext(...)'因为它是null

dzhpxtsq  于 2023-04-29  发布在  React
关注(0)|答案(2)|浏览(551)

im facing Uncaught TypeError:无法解构“React2”的属性“basename”。useContext(...)’,因为它是空的。在代码的链接组件中

import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';

import { styles } from '../styles';
import { navLinks } from '../constansts';
import { logo, menu, close } from '../assets';

const Navbar = () => {
  const [active, setActive] = useState('');
  return (
    <nav className={`${styles.paddingX} w-full flex items-center py-5 fixed top-0 z-20     bg-primary`}>
      <div className="w-full flex justify-between items-center max-w-7x1 max-auto">
        <Link
          to="/"
          className="flex items-center gap-2"
          onClick={() => {
            setActive('');
            window.scrollTo(0, 0);
          }}
        >
          <img alt="logo" />
        </Link>
      </div>
    </nav>
  );
};

export default Navbar;

我不知道怎么修,谁能告诉我怎么修吗

lvmkulzt

lvmkulzt1#

您正在使用react-router-dom中的Link,但您的应用未被BrowserRouter Package 。您的index.js

import { BrowserRouter } from 'react-router-dom'

render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root')
)
zkure5ic

zkure5ic2#

请确保在App上正确使用路由。js并将navbar组件放入BrowserRouter中。作为一个例子,让我们假设你的应用程序。js类似于:

function App() {
  return (
  <div className="App">
    
    <Router>
      <Routes>
        <Route path="/" element={<HomePage/>}/>
        <Route path="/x" element={<x/>}/>
        <Route path="/y" element={<y/>}/>
        <Route path="/z" element={<z/>}/>
        <Route path="/*" element={<NotFound/>}/>
      </Routes>
    </Router>
  </div>);
}

export default App;

然后:

function App() {
  return (
  <div className="App">
    
    <Router>
      <Routes>
        <NavBar/>
        <Route path="/" element={<HomePage/>}/>
        <Route path="/x" element={<x/>}/>
        <Route path="/y" element={<y/>}/>
        <Route path="/z" element={<z/>}/>
        <Route path="/*" element={<NotFound/>}/>
      </Routes>
    </Router>
  </div>);
}

export default App;

一定要添加导入!
edit:在 Package 路由之前,我导入BrowserRouter作为Router,因为它有助于我理解代码,这就是为什么它被这样声明

相关问题