React Router在Route元素中使用Link时呈现错误



我正在使用"react-router-dom"; "^5.2.0",我将得到这个错误。

Error: You cannot render a <Router> inside another <Router>. You never need more than one

代码如下:

App.js

import './App.css';
import SpiderSolitaire from './Pages/SpiderSolitaire';
import Home from './Components/Home/Home';
import {BrowserRouter as Router,Routes,Route} from 'react-router-dom';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />}/>
<Route path="/game" element={<SpiderSolitaire />}/>
</Routes>
</Router>
);
}
export default App;

Home.js

import React from "react";
import { BrowserRouter as Link } from 'react-router-dom';
import { useNavigate  } from 'react-router-dom';
import "./Home.scss";
import PlayingCards from "../../assets/spider.png"
import Spider from "../../assets/bb.png"
function Home() {
return (
<div data-test="home-app" className="home">
<h1 data-test="home-header">Welcome Reversed Spider SpiderSolitaire</h1>
<div data-test="home-image-wrapper" className="flex">
<img data-test="home-image" src={PlayingCards} alt="playingCards" width="300"/>
</div>
<div data-test="home-rules-wrapper" className="rules">
<h2 data-test="home-rules-header">How To Play ?</h2>
<ul>
<li data-test="home-rule-1">To win a hand, the cards must always be arranged in the 
order A, 2, 3, 4, 5, 6, 7, 8 ,9 , 10, J, Q, K.</li>
<li data-test="home-rule-2">When the game is deadlocked or when you need a card, click 
on the top left and after that 10 new cards are placed on the deck.</li>
<li data-test="home-rule-3">Of the fifty-four cards laid out on the table at the 
beginning of the game, only the top cards are face-up.</li>
<li data-test="home-rule-4">If the face of the face up card changes, the face of the 
previous card is revealed.</li>
<li data-test="home-rule-5">To win the game, there must be 8 sets of hands at the end 
of the game.</li>
</ul>
</div>
<Link to={"/game"}>
<button data-test="home-game-button" className="startGame" >Start to  Game</button>
</Link>
</div>
);
}
export default Home;

当我删除Home中的Link并使用useNavigate时,它工作了。但问题是,当我测试代码时,它给出了这样的错误:

TypeError: (0 , _reactRouterDom.useNavigate) is not a function
7 | function Modal( ) {
8 |
>  9 |   const navigate = useNavigate();
|                    ^
10 |   const playAgain = () =>{
11 |     navigate.push("/");
12 |   }

是否有可能的方式直接到用户路由?或者How I can do it different

问题是您的import语句在Home.js

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

,

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

相关内容

最新更新