反应路由器“无法读取未定义的属性“推送" [英] react-router " Cannot read property 'push' of undefined"
问题描述
我对反应和反应路由器很陌生.
react 的问题在于,在我的应用程序的某些页面上,react-router 正在工作,并且有些页面会出现这样的错误:无法读取未定义的属性 'push'".
我正在使用 react 0.14.1
我的路由代码如下所示:
render(<路由器历史={hashHistory}><Route path="/" component={Loginpanel}/><Route path="Index" component={Index}/><Route path="Form" component={Form}/><Route path="Checkindex" component={Index}/><Route path="Signup" component={Signup}/><Route path="Admin" component={Admin}/><Route path="AdminEditDetails" 组件={AdminEditDetails}/><Route path="AdminDetails" 组件={AdminDetails}/></路由器>,document.getElementById('js-main'));
我的组件现在是这样的:
class App 扩展 React.Component {构造函数(道具){超级(道具);this.state= {评论:AppStore.getAll();};}componentWillMount() {var 长度 = this.state.comments.length;var firstnumber = 长度 - 4;如果(长度== 0){console.log("来了");this.props.router.push('/');}别的{console.log('正常工作');}}}
谁能帮我解决这个问题?谢谢.
您的应用的 props 中没有 Router 的实例,这导致您无法读取未定义的属性 'push'
.
我假设您正在导入 withRouter 以获取路由器的实例,因此如果您仍想使用它,则需要将组件包装在其中...(例如 这里 但不建议)
相反,以编程方式导航的更好方法是使用
import { hashHistory } from 'react-router;'...hashHistory.push('/');
在您的 componentWillMount
生命周期事件中.
文档在这里>
希望这有帮助!
i am quite new to react and react-router.
Problem with react is here that, on some pages of my application react-router is working and some giving error like this: "Cannot read property 'push' of undefined".
i am using react 0.14.1
My routing code looks like this:
render(
<Router history={hashHistory}>
<Route path="/" component={Loginpanel}/>
<Route path="Index" component={Index}/>
<Route path="Form" component={Form} />
<Route path="Checkindex" component={Index}/>
<Route path="Signup" component={Signup}/>
<Route path="Admin" component={Admin}/>
<Route path="AdminEditDetails" component={AdminEditDetails}/>
<Route path="AdminDetails" component={AdminDetails}/>
</Router>,
document.getElementById('js-main'));
My component is like this now:
class App extends React.Component {
constructor(props) {
super(props);
this.state= {
comments: AppStore.getAll();
};
}
componentWillMount() {
var length = this.state.comments.length;
var firstnumber = length - 4;
if(length == 0){
console.log("here comes");
this.props.router.push('/');
}
else{
console.log('work normally');
}
}
}
Can anyone help me with this? Thanks.
Your app does not have an instance of Router in its props which is giving you Cannot read property 'push' of undefined
.
I'm assuming you're importing withRouter to get the instance of the Router so you'd need to wrap the component in that if you still want to use that... (example here but not suggested)
Instead, a better approach to programmatically navigating is to use
import { hashHistory } from 'react-router;'
...
hashHistory.push('/');
in your componentWillMount
lifecycle event.
The docs are here
Hope this helps!
这篇关于反应路由器“无法读取未定义的属性“推送"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!