情况:在app中引入了一个footerNav组件(路由也都引入了),然后在footerNav中点击按钮跳转,结果报错:
Uncaught TypeError: Cannot read property 'push' of undefined
解决:
方式1 通过propTypes将父组件app对象传入子组件footerNav
import PropTypes from 'prop-types';
class MenuHeader extends React.Component {
static propTypes = {
parentThis: PropTypes.object.isRequired,
}
...
/*这时候footerNav点击跳转:*/
this.props.parentThis.props.history.push(routerName);
...
}
export default MenuHeader;
上面这种方式比较...low?下面使用换个方式
使用react-router-dom的withRouter包组件
import {withRouter } from 'react-router-dom'
class MenuHeader extends React.Component {
...
/*这时候footerNav点击跳转:*/
this.props.history.push(routerName);
...
}
export default withRouter(MenuHeader);
本文介绍了解决React应用中footerNav组件跳转时出现的TypeError: Cannot read property 'push' of undefined错误的方法。提供了两种解决方案,一是通过propTypes传递父组件的history对象,二是使用withRouter高阶组件。
2万+

被折叠的 条评论
为什么被折叠?



