我对react和react-router非常陌生。
react的问题是,在我的应用程序react-router的一些页面上,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');
}
}
}有人能帮我吗?谢谢。
发布于 2016-08-28 02:08:56
发布于 2016-08-28 04:22:34
直接从react-router使用hashHistory当然是一种选择,但这会使单元测试更加痛苦。浏览器历史记录通常在运行测试的上下文中不可用,并且模拟出一个道具比模拟出一个全局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('/');。
发布于 2018-07-30 14:14:21
如果您使用分部组件,并像<Header />一样调用它,那么您应该用<Header {...this.props} />替换它
https://stackoverflow.com/questions/39184049
复制相似问题