【发布时间】:2017-05-02 13:25:02
【问题描述】:
当我导出一个组件时:
export default class Link extends React.Component{
onLogout() {
this.props.history.push('/');
}
与此相关的按钮正确更改了 react-router v4 中的页面。
但是,在我的 main.js 文件中,我目前正在尝试获得类似的内容:
if (insert conditional here) {
this.props.history.push('/');
}
工作。但它只是给我一个类型错误。
'Uncaught TypeError: Cannot read property 'history' of undefined'.
我确实安装了所有正确的依赖项,并且它在我的其他组件中运行良好。我目前在主 js 文件中有这个 if 语句(它是我练习理解 v4 的一个小项目),所以我认为这可能是因为我没有扩展一个类。
有谁知道为什么相同的代码不能在主文件中运行,有没有解决方法?所有 react-router v4 的变化都让这个菜鸟感到困惑。
【问题讨论】:
-
确保
this方法中onLogout的上下文正确设置为类。一种方法是console.log(this.props)。 -
使用 browserHistory 代替历史记录
标签: reactjs react-router