不变违规:您不应该使用< Switch>在<路由器>之外 [英] Invariant Violation: You should not use <Switch> outside a <Router>

查看:68
本文介绍了不变违规:您不应该使用< Switch>在<路由器>之外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我不知道如何解决,运行npm测试时出现此错误不变违规:您不应该使用< Switch>在<路由器> 之外。问题是什么,我该如何解决?我运行的测试是反应附带的标准app.test.js

I have a problem that I dont know how to solve, I get this error when running npm test Invariant Violation: You should not use <Switch> outside a <Router>. What can the problem be and how can I solve it? The test I run is the standard app.test.js that comes with react

class App extends Component {
  render() {
    return (
      <div className = 'app'>
        <nav>
          <ul>
            <li><Link exact activeClassName="current" to='/'>Home</Link></li>
            <li><Link exact activeClassName="current" to='/TicTacToe'>TicTacToe</Link></li>
            <li><Link exact activeClassName="current" to='/NumGame'>Quick Maths</Link></li>
            <li><Link exact activeClassName="current" to='/HighScore'>Highscore</Link></li>
            <li><Link exact activeClassName="current" to='/Profile'>Profile</Link></li>
            <li><Link exact activeClassName="current" to='/Login'>Sign out</Link></li>
          </ul>
        </nav>
        <Switch>
          <Route exact path='/' component={Home}></Route>
          <Route path='/TicTacToe' component={TicTacToe}></Route>
          <Route path='/NumGame' component={NumberGame}></Route>
          <Route path='/HighScore' component={HighScore}></Route>
          <Route path='/Profile' component={Profile}></Route>
          <Route path='/Login' component={SignOut1}></Route>
        </Switch>
      </div>
    );
  }
};


推荐答案

错误是正确的。你需要用 BrowserRouter HashRouter Switch c>, MemoryRouter 。这是因为 BrowserRouter 和替代品是所有路由器组件的常见低级接口,他们使用HTML 5 历史记录 API,你需要在你的路线之间来回导航。

The error is correct. You need to wrap the Switch with BrowserRouter or other alternatives like HashRouter, MemoryRouter. This is because BrowserRouter and alternatives are the common low-level interface for all router components and they make use of the HTML 5 history API, and you need this to navigate back and forth between your routes.

尝试这样做

import { BrowserRouter, Switch, Route } from 'react-router-dom';

然后包装这样的一切

<BrowserRouter>
 <Switch>
  //your routes here
 </Switch>
</BrowserRouter>

这篇关于不变违规:您不应该使用&lt; Switch&gt;在&lt;路由器&gt;之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆