React-Router v4:无法读取未定义的属性“route”

时间:2017-04-03 03:04:29

标签: react-router

我想点击按钮时重定向,所以我使用withRouter来访问历史道具。

但我收到错误:

Uncaught TypeError: Cannot read property 'route' of undefined
  at Route.computeMatch (react-router.js:1160)
使用withRouter HOC包装组件时出现

错误。 如果我删除withRouter函数,它就可以正常工作。

我的代码如下所示:

class App extends Component {

// ...some unrelated functions

handleTitleTouchTap = e => {
    e.preventDefault()
    const { history } = this.props
    history.push('/')
}

render() {
                //...other components
        <Router>
            <div>      
                <Switch>
                    <Route exact={true} path="/" component={Home} />
                    <Route path="/search" component={Search}/>
                    <Route path="/gamelist/:listId" component={GameListDetail}/>
                    <Route path="/game/:gameId" component={GameDetail}/>
                    <Route path="/manageuser" component={ManageUser} />
                    <Route path="/addgamelist" component={AddGameList} />
                    <Route path="/addgame" component={AddGame} />
                    <Route path="/test" component={Test} />
                    <Route component={NoMatch} />
                </Switch>
                <LoginForm isLoginFormOpen={isLoginFormOpen} closeLoginForm={closeLoginForm} handleLogin={handleLogin}/>
                <RegisterForm isRegisterFormOpen={isRegisterFormOpen} closeRegisterForm={closeRegisterForm} register={register}/>
            </div>
        </Router>
    )
}


const mapStateToProps = state => ({
    //some props
})
const mapDispatchToProps = dispatch => ({
    //some functions
})
const Container = connect(mapStateToProps, mapDispatchToProps)(App)

export default withRouter(Container)

1 个答案:

答案 0 :(得分:11)

我遇到了同样的问题,我解决了将包裹的组件包含在(x1, , 1:5) : subscript out of bounds组件中(即Router)。

在您的示例中,它将变为:

BrowserRouter

此处文档的工作示例:https://codepen.io/pietro909/pen/RVWmwZ

我还在回购中打开了一个问题,因为我认为文档中的示例不够明确https://github.com/ReactTraining/react-router/issues/4994