尝试将反应路由器v4与redux一起使用并遇到此错误,似乎是在关注文档,无法在其上找到任何信息,所以我不知所措:
未捕获的TypeError:无法读取未定义的属性“route”
这是我的代码:
import React, {Component} from 'react';
import {
BrowserRouter as Router,
Route,
Link,
withRouter
} from 'react-router-dom'
import Menu from './Menu';
import { connect } from "react-redux";
import Play from './Play';
class Manager extends Component {
render() {
return(
<Router>
<div>
<Route exact path="/" component={Menu}/>
<Route path="/menu" component={Menu}/>
<Route path="/play" component={Play}/>
</div>
</Router>
)
}
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Manager));
这是完整的错误:
game.js:26838 Uncaught TypeError: Cannot read property 'route' of undefined
at Route.computeMatch (game.js:26838)
at new Route (game.js:26815)
at game.js:15322
at measureLifeCyclePerf (game.js:15102)
at ReactCompositeComponentWrapper._constructComponentWithoutOwner (game.js:15321)
at ReactCompositeComponentWrapper._constructComponent (game.js:15307)
at ReactCompositeComponentWrapper.mountComponent (game.js:15215)
at Object.mountComponent (game.js:7823)
at ReactCompositeComponentWrapper.performInitialMount (game.js:15398)
at ReactCompositeComponentWrapper.mountComponent (game.js:15285)
答案 0 :(得分:4)
在这里,您使用的是react-router-dom最新版本4.0.0以上。
因此,没有可用的路由器。您需要在此版本中使用BrowserRouter。
您的代码将
import React, {Component} from 'react';
import {
Switch,
Route,
Link,
withRouter
} from 'react-router-dom'
import Menu from './Menu';
import { connect } from "react-redux";
import Play from './Play';
class Manager extends Component {
render() {
return(<div>
<Switch>
<Route exact path="/" component={Menu}/>
<Route path="/menu" component={Menu}/>
<Route path="/play" component={Play}/>
</Switch></div>
)
}
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Manager));
并在index.js文件中使用BrowserRouter来呈现此Component
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render((<BrowserRouter><Manager/></BrowserRouter>), document.getElementById('root'));
答案 1 :(得分:2)
将路由器更改为名为“react-router-dom”
的新路由器4.0使用npm / yarn安装模块“react-router-dom”,像这样定义你的路由器..
不要忘记进口。 从'react-router-dom'导入{BrowserRouter,Route};
<BrowserRouter>
<div>
<Route exact path="/" component={Menu}/>
<Route path="/menu" component={Menu}/>
<Route path="/play" component={Play}/>
</div>
</BrowserRouter>
答案 2 :(得分:0)
您不需要使用比实际路由器更高的withRouter :) 只需删除它:
export default connect(mapStateToProps, mapDispatchToProps)(Manager);
如果要访问嵌套在Route中的组件内的历史信息,则需要使用withRouter HOC。您可以在此处找到详细信息:https://reacttraining.com/react-router/web/api/withRouter
答案 3 :(得分:0)
所以我在我的本地服务器上运行它,当我从它运行的webpack服务器上运行它时。
答案 4 :(得分:0)
我通过在我的<Navigation />
<Router></Router>
来解决此问题