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

前端之家收集整理的这篇文章主要介绍了React-Router v4:无法读取未定义的属性“route”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我点击按钮时我想重定向,所以我使用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)
我有同样的问题,我解决了它将包装组件包含在路由器组件(即BrowserRouter)中.

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

// assuming this file is Container.js
export default withRouter(Container)


// index.js
import Container from './Container'

render(
    <BrowserRouter>
        <Container/>
    </BrowserRouter>,document.getElementById('root')
 )

来自这里的文档的工作示例:https://codepen.io/pietro909/pen/RVWmwZ

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

原文链接:https://www.f2er.com/react/301095.html

猜你在找的React相关文章