对 BrowserRouter 组件中的无效 Hook 调用警告做出反应

问题描述 投票:0回答:1

react.development.js:209 警告:无效的钩子调用。钩子只能在函数组件的主体内部调用。发生这种情况可能是由于以下原因之一:

  1. 您的 React 和渲染器版本可能不匹配(例如 React DOM)
  2. 你可能违反了 Hooks 规则
  3. 您可能在同一个应用程序中拥有多个 React 副本

import React from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faImage } from '@fortawesome/free-solid-svg-icons';
import "./App.css";
import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-dom';

const galleryData = [
  {
    id: 1,
    imageUrl: 'https://images.unsplash.com/photo-1593053109521-e86fd978ba96?q=80&w=1674&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D',
    title: 'Beautiful Sunset',
    description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
}
];

const Home = () => (
  <div className="App">
    <Nav />
    <div className='heading' style={{ display: "flex" }}>
      <FontAwesomeIcon icon={faImage} size='lg' />
      <h2>Image Gallery</h2>
    </div>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
    <button title='View More'>
      <Link to="/gallery">See Images</Link>
    </button>
  </div>
);

const Gallery = () => (
  <div className="App">
    <Nav />
    <div className='heading' style={{ display: "flex" }}>
      <FontAwesomeIcon icon={faImage} size='lg' />
      <h2>Image Gallery</h2>
    </div>
    <div className='gallery'>
      {galleryData.map(item => (
        <div key={item.id} className="gallery-item">
          <img src={item.imageUrl} alt={item.title} />
          <div className="caption">
            <h1>{item.title}</h1>
            <p>{item.description}</p>
          </div>
        </div>
      ))}
    </div>
  </div>
);

const Nav = () => (
  <nav>
    <ul>
      <li>
        <Link to="/">Home</Link>
      </li>
      <li>
        <Link to="/gallery">Gallery</Link>
      </li>
      {/* Add more navigation links as needed */}
    </ul>
  </nav>
);

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" exact component={Home} />
        <Route path="/gallery" component={Gallery} />
      </Routes>
    </Router>
  )};

export default App;

我已经检查了警告消息中提到的常见原因,例如版本不匹配和违反 Hooks 规则,但无法确定根本原因。该错误似乎与 BrowserRouter 组件有关。

任何有关如何调试和解决此问题的见解或建议将不胜感激。

reactjs react-hooks react-router-dom react-dom
1个回答
0
投票

尝试使用 BrowserRouter 的原始名称,而不是分配的 Router 名称。 因为React Router Dom库只是导出了自己库的Router函数,可能有些东西是冲突的。

© www.soinside.com 2019 - 2024. All rights reserved.