【发布时间】:2021-08-20 07:36:15
【问题描述】:
我正在使用“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;
当我删除主页中的链接并使用 useNavigate 时,它可以工作。但问题是当我测试代码时会出现这样的错误。
TypeError: (0 , _reactRouterDom.useNavigate) is not a function
7 | function Modal( ) {
8 |
> 9 | const navigate = useNavigate();
| ^
10 | const playAgain = () =>{
11 | navigate.push("/");
12 | }
是否有任何可能的方式来引导用户进行路由?或者我可以如何做不同的事情。
【问题讨论】:
-
您确定您使用的是
react-router-domv5.2.0 吗?Routes和useNavigate是 v6 中的新功能。您的问题是在正常运行您的应用程序时出现的,还是仅在单元测试期间出现?另外,在 home.js 中,你是import { BrowserRouter as Link } from 'react-router-dom';这显然是一个错误。 -
投票结束为“不可复制或由错字引起”。干杯。
标签: reactjs react-router enzyme react-router-dom