我有以下代码
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'))
我正在学习一个教程,但是其标题部分的工作原理如上所述;但是,我在控制台中收到一个错误,页面上没有任何呈现。
VM84 bundle.js:40892 Uncaught Error: Invariant failed: You should not use <Link> outside a <Router>
我相信我必须对withRouter
做些事情,但不确定如何进行。
我还有一个指向代码所在的github存储库的链接,因为我正在使用webpack和babel捆绑我的项目。 https://github.com/altafmquadri/expensify-app。
错误告诉您Links
无法在Router
外部渲染。所有链接都在标头组件中呈现。将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>
);
Header组件必须位于Router
内才能访问Header组件内的链接。
<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>