我是新来的反应和反应路由器。
react的问题在于,在我的应用程序的某些页面上,react-router正在运行,并且出现一些类似的错误:“无法读取未定义的属性’push’”。
我正在使用反应0.14.1
我的路由代码如下所示:
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'));
我的组件现在是这样的:
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'); } } }
谁能帮我这个?谢谢。
您的应用程序中没有提供支持的Router实例Cannot read property 'push' of undefined。
Cannot read property 'push' of undefined
我假设您要导入withRouter以获取Router的实例,因此如果您仍然想使用该组件,则需要将其包装起来…(此处为示例,但不建议使用)
相反,以编程方式导航的更好方法是使用
import { hashHistory } from 'react-router;' ... hashHistory.push('/');在您的componentWillMount生命周期事件中。
import { hashHistory } from 'react-router;' ... hashHistory.push('/');
componentWillMount
文档在这里
希望这可以帮助!