我对 React 和 React-router 很陌生。
react 的问题在于,在我的应用程序的某些页面上,react-router 正在运行,但有些页面会出现这样的错误:“无法读取未定义的属性‘push’”。
我正在使用 React 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');
}
}
}
谁能帮我解决这个问题?谢谢。
最佳答案
直接从 react-router
使用 hashHistory
当然是一种选择,但它会使单元测试更加痛苦。
浏览器历史记录在运行的上下文测试中通常不可用,并且模拟一个 prop 比模拟一个全局 API 更容易。
考虑使用 react-router
提供的 withRouter
高阶组件(自 v2.4.0
起)。
import { withRouter } from 'react-router';
class App extends Component {
(...)
}
export default withRouter(App);
您的 App
类将通过 props 接收 router
并且您可以安全地执行 this.props.router.push('/');
.
关于javascript - react-router "Cannot read property ' push' of undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39184049/