未捕获的错误:不变失败:您不应在<Router>外使用<NavLink>

时间:2019-11-20 11:31:37

标签: reactjs react-router-dom storybook

invariant failed

它表示我在NavLink之外使用Router,但是当您查看代码时。我只是在导入组件(Home),而该组件实际上又在路线内部。但是它会引发错误。

index.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';


ReactDOM.render(<App />, document.getElementById('root'));

App.tsx

import React from 'react';
import { BrowserRouter, Route, Switch } from "react-router-dom";
import { Register } from './pages/register/register'
import { Login } from './pages/login/login'
import { Home } from './pages/home/home'

const App: React.FC = () => {
  return (
    <div id="app-root">
      <BrowserRouter>
        <Switch>
          <Route path="/register" exact component={Register} />     
          <Route path="/login" exact component={Login} />
          <Route path="/" exact component={Home} />
        </Switch>
      </BrowserRouter>
    </div>
  );
}

export default App;

Home.txs

import React from 'react';
import { BrowserRouter, Route, Switch, NavLink } from "react-router-dom";
import classNames from 'classnames'
import styles from './home.module.css';
import logoFull from 'assets/img/pangolin-logo-full.png';
import logoText from 'assets/img/pangolin-title-text-dark.png';
import homeMessages from './home.messages';

export const Home = () => {
   return (
      <div className={styles.homePage}>
          <NavLink to="/register" className={classNames(styles.registrationButton, styles.link)}>
               {homeMessages.register()} 
          </NavLink>
          <NavLink to="/login" className={classNames(styles.loginButton, styles.link)}>
               {homeMessages.login()}
          </NavLink>
      </div>

   );
 };

1 个答案:

答案 0 :(得分:0)

我认为,如果您将NavLink移到Switch之外,将会解决您的问题。