您的位置:首頁技術文章
文章詳情頁

javascript - Reactjs關于函數內跳轉 this.context.router.push(path)的問題

瀏覽:110日期:2023-02-17 10:31:11

問題描述

請教各位師兄了。我創建了一個組件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時始終建議這么寫 }}

標簽: JavaScript
相關文章:
国产综合久久一区二区三区