我通过在命令提示符窗口中运行以下代码片段在我的项目上安装了 react-router
:
npm install react-router
我发现react-router
安装成功,因为安装没有错误,而且输出是:
- react-router@4.3.1 updated 1 package in 19.53s
基于 tutorial ,我将 Index.js 设置为如下代码:
ReactDOM.render((
<Router history = {browserHistory}>
<Route path = "/" component = {App}>
<IndexRoute component = {Home} />
<Route path = "home" component = {Home} />
<Route path = "about" component = {About} />
<Route path = "contact" component = {Contact} />
</Route>
</Router>
), document.getElementById('app'))
现在,当我想编译/构建我的应用程序时,会发生以下错误:
./src/index.js
Line 14: 'Router' is not defined react/jsx-no-undef
Line 14: 'browserHistory' is not defined no-undef
Line 15: 'Route' is not defined react/jsx-no-undef
Line 16: 'IndexRoute' is not defined react/jsx-no-undef
Line 17: 'Route' is not defined react/jsx-no-undef
Line 18: 'Route' is not defined react/jsx-no-undef
Line 19: 'Route' is not defined react/jsx-no-undef
我知道编译器找不到路由类,并且我在谷歌和这个社区上搜索了像我的问题这样的问题,但实际上我的搜索结果没有帮助。感谢您的回复。
最佳答案
在调用它们之前,您需要导入 Router、Route 和 index.js 文件
import { Router, Route } from "react-router";
React-Router v4 不支持 IndexRoute,您可以使用精确的 Route 来代替 IndexRoute,例如
<Route exact path={path} component={Component} />
编辑:
react-router v4 不支持 browserHistory,因此这里有替代解决方案 https://github.com/ReactTraining/react-router/blob/25776d4dc89b8fb2f575884749766355992116b5/packages/react-router/docs/guides/migrating.md#the-router
关于reactjs - React-JS/react-router-dom中的路由问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52772413/