TypeError: Cannot read property 'location' of undefined in react^16.13.1 react-router-dom^5.2.0

TypeError: Cannot read property 'location' of undefined in react^16.13.1 react-router-dom^5.2.0

我正在尝试使用 "react": "^16.13.1", "react-router-dom": "^5.2.0", "react-transition-组”:“^4.4.1”。但是出现错误提示“TypeError: Cannot read 属性 'location' of undefined”,如何解决?

Error

MainComponent.js

...
    return (
        <div>
            <Header />
            <TransitionGroup>
                <CSSTransition key={this.pops.location.key} classNames="page" timeout={300}>
                    <Switch>
                        <Route path='/home' >{HomePage}</Route>
                        <Route exact path='/contactus' component={() => <Contact resetFeedbackForm={this.props.resetFeedbackForm}/>} />
                        <Route exact path='/menu' component={() => <Menu dishes={this.props.dishes} />} />
                        <Route path='/menu/:dishId' component={DishWithId} />
                        <Route exact path='/aboutus' component={() => <About leaders={this.props.leaders} />} />
                        <Redirect to="/home" />
                    </Switch>
                </CSSTransition>
            </TransitionGroup>
            <Footer />
        </div>
    );
}
...

如何获取位置密钥?

您可以使用 useHistory 挂钩或使用历史包 https://www.npmjs.com/package/history

谢谢大家。我找到了答案。我将代码移动到应用动画的 AnimatedSwitch 对象并使用 withRouter(({ location }) 获取位置并且它正常工作。

class Main extends Component{
render(){
.......
.......
const AnimatedSwitch = withRouter(({ location }) => (
        <TransitionGroup>
            <CSSTransition
                key={location.key}
                classNames="page"
                timeout={1000}
            >
                <Switch>
                    <Route path='/home' >{HomePage}</Route>
                    <Route exact path='/contactus' component={() => <Contact     resetFeedbackForm={this.props.resetFeedbackForm} />} />
                    <Route exact path='/menu' component={() => <Menu dishes={this.props.dishes} />} />
                    <Route path='/menu/:dishId' component={DishWithId} />
                    <Route exact path='/aboutus' component={() => <About leaders={this.props.leaders} />} />
                    <Redirect to="/home" />
                </Switch>
            </CSSTransition>
        </TransitionGroup>
    ));

    return (
        <div>
            <Header />
            <AnimatedSwitch />
            <Footer />
        </div>
    );
}
}

您可以找到更多关于在 React 路由器路由之间添加动画的信息 here

.......表示这里代码较多