javascript - Reactjs关于函数内跳转 this.context.router.push(path)的问题
问题描述
请教各位师兄了。我创建了一个组件Component,并在内部中的一个ajax成功回调内,写了this.context.router.push('/user/list')类似的跳转功能。同时在组件外写了Component.contextTypes={ router: React.PropTypes.object.isRequired }。ajax也成功请求了,但是页面并没有跳转,有点疑问了。。。代码结构类似:
class Component extends React.Component{ ... success: function(data) {alert(data);this.context.router.push(...) }}Component.contextTypes={ router: React.PropTypes.object.isRequired}
问题解答
回答1:是不是拿不到this?. 试试用 success()->()
回答2:这里写一下在网上查找答案时遇到的坑,同时也是为了告诉后来遇到同样或者相似问题的小白吧,还请相关帖子管理人员别删:在 Component.contextTypes这儿,我查到过有人把它以这种方式写到过组件内部:
class Component extends React.Component{ [有些人写static有些人又不写static] contentTypes: {router: React.PropTypes.object.isRequired } ... this.context.router.push(...)}
然而这么做我这儿始终出问题,就是报错 Cann’t read the property ’push’ is not defined。不太明显为啥呢,先记下来再说吧
回答3:'Cann’t read the property ’push’ is not defined'这个错误确保contextTypes写好了并且构造函数调用super是没有把context弄丢
class Component { constructor(props, context) { super(...arguments) // 这样才行,如果只写props, 会把context 弄丢,所以super时始终建议这么写 }}
相关文章:
1. html - 爬虫时出现“DNS lookup failed”,打开网页却没问题,这是什么情况?2. javascript - echart+百度地图3. css - autoprefixer没有添加web-kit前缀4. 无效的配置对象已使用与API模式不匹配的配置对象初始化了Webpack5. web - Rails3使用form_for时出现undefined method `*_path’错误。6. javascript 开发百度地图7. nginx - 关于vue项目部署到ngnix后出现的问题8. angular.js - 百度爬虫如何处理“#”符号?9. nosql - mongodb 多组数据不固定字段查询问题 [百度党请绕道]10. font-family - 我引入CSS3自定义字体没有效果?
