我已经在Web主机上启动并运行了一个React网站,我试图向其中添加react router
,所以我使用react-router-dom
安装了npm
,但是却收到此错误,但没有有关错误消息或其他内容的进一步说明。
我尝试将react-router-dom
更改为旧版本的react-router
,但是遇到了不同的错误,所以我返回了react-router-dom。
// src/Container3d.js
import React, { Component } from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom'
import Scene3d from './Scene3d'
import Model2 from './Model2'
class Container3d extends Component {
render() {
return (
<Router>
<div className="container3d">
<Route path="/model-1" component={Scene3d} />
<Route path="/model-2" component={Model2} />
</div>
</Router>
)
}
}
export default Container3d
///////////////////////////////////////////////////////
// src/App.js
import { Link } from 'react-router-dom'
class App extends Component {
render() {
return (
<ul>
<li>
<Link to="/model-1">model-1</Link>
</li>
<li>
<Link to="/model-2">model-2</Link>
</li>
</ul>
)
}
}
export default App
错误消息:
react-dom.production.min.js:198 Error: Invariant failed
at invariant (tiny-invariant.esm.js:9)
at react-router-dom.js:154
at Tg (react-dom.production.min.js:184)
at bi (react-dom.production.min.js:232)
at ci (react-dom.production.min.js:233)
at Di (react-dom.production.min.js:249)
at Yh (react-dom.production.min.js:248)
at Xh (react-dom.production.min.js:245)
at qf (react-dom.production.min.js:243)
at Ji (react-dom.production.min.js:253)
qh @ react-dom.production.min.js:198
react-dom.production.min.js:248 Uncaught Error: Invariant failed
at invariant (tiny-invariant.esm.js:9)
at react-router-dom.js:154
at Tg (react-dom.production.min.js:184)
at bi (react-dom.production.min.js:232)
at ci (react-dom.production.min.js:233)
at Di (react-dom.production.min.js:249)
at Yh (react-dom.production.min.js:248)
at Xh (react-dom.production.min.js:245)
at qf (react-dom.production.min.js:243)
at Ji (react-dom.production.min.js:253)
答案 0 :(得分:2)
您必须用App
包装BrowserRouter
组件。
看下面的代码。
import { Link, BrowserRouter as Router } from 'react-router-dom'
class App extends Component {
render() {
return (
<Router>
<ul>
<li>
<Link to="/model-1">model-1</Link>
</li>
<li>
<Link to="/model-2">model-2</Link>
</li>
</ul>
</Router>
)
}
}
export default App
在这里,我为您创建了一个小型演示!
https://stackblitz.com/edit/react-router-sbhdpk
希望这对您有用!