react-router-dom 出现错误,我无法解决

Getting an error with react-router-dom, that I can't solve

我有以下代码

import React from 'react';
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom'
import 'normalize.css/normalize.css'
import './styles/styles.scss'

const ExpenseDashboardPage = () => (
    <div>
        This is from my dashboard component
    </div>
)

const AddExpensePage = () => (
    <div>
        This is from my add expense component
    </div>
)

const EditExpensePage = () => (
    <div>
        This is for editing expenses component
    </div>
)

const HelpPage = () => (
    <div>
        This is help component
    </div>
)

const NotFoundPage = () => (
    <div>
        404! <Link to='/'>Go Home</Link>
    </div>
)

const Header = () => (
    <header>
        <h1>Expensify</h1>
        <Link to="/">Home</Link>
        <Link to='/create'>Add Expense</Link>
        <Link to='/edit'>Edit Expense</Link>
        <Link to='/help'>Help</Link>
    </header>
)

const routes = (
    <div>
        <Header />
        <Router>
            <Switch>
                <Route exact path='/' component={ExpenseDashboardPage} />
                <Route path='/create' component={AddExpensePage} />
                <Route path='/edit' component={EditExpensePage} />
                <Route path='/help' component={HelpPage} />
                <Route component={NotFoundPage} />
            </Switch>
        </Router>
    </div>
)


ReactDOM.render(routes, document.getElementById('app'))

我正在学习教程,但是他们的 header 组件和上面一样工作;但是,我在控制台中收到错误消息,页面上没有任何内容。

VM84 bundle.js:40892 Uncaught Error: Invariant failed: You should not use <Link> outside a <Router>

我想我必须用 withRouter 做点什么,但不确定如何进行。

我有一个 link 到 github 代码库,因为我正在使用 webpack 和 babel 来捆绑我的项目。 https://github.com/altafmquadri/expensify-app

Header 组件需要位于 Router 内,以便能够访问 Header 组件内的 link。

    <Router>
      <Header />
      <Switch>
        <Route exact path="/" component={ExpenseDashboardPage} />
        <Route path="/create" component={AddExpensePage} />
        <Route path="/edit" component={EditExpensePage} />
        <Route path="/help" component={HelpPage} />
        <Route component={NotFoundPage} />
      </Switch>
    </Router>

错误告诉您 Links 无法在 Router 之外呈现。所有链接都在 header 组件中呈现。将 Header 移动到 Router.

const routes = (
  <div>
    <Router>
      <Header />
      <Switch>
        <Route exact path='/' component={ExpenseDashboardPage} />
        <Route path='/create' component={AddExpensePage} />
        <Route path='/edit' component={EditExpensePage} />
        <Route path='/help' component={HelpPage} />
        <Route component={NotFoundPage} />
      </Switch>
    </Router>
  </div>
);