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. django - 后臺返回的json數據經過Base64加密,獲取時用python如何解密~!2. node.js - node 客戶端socket一直報錯Error: read ECONNRESET,用php的socket沒問題哈。。3. tp6表單令牌4. angular.js - 如何通俗易懂的解釋“依賴注入”?5. 老哥們求助啊6. 我的html頁面一提交,網頁便顯示出了我的php代碼,求問是什么原因?7. css3 - 請問一下在移動端CSS布局布局中通常需要用到哪些元素,屬性?8. docker 17.03 怎么配置 registry mirror ?9. 我在centos容器里安裝docker,也就是在容器里安裝容器,報錯了?10. 在MySQL中新增字段時,報錯??
