javascript - Reactjs關于函數(shù)內(nèi)跳轉 this.context.router.push(path)的問題
問題描述
請教各位師兄了。我創(chuàng)建了一個組件Component,并在內(nèi)部中的一個ajax成功回調(diào)內(nèi),寫了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:這里寫一下在網(wǎng)上查找答案時遇到的坑,同時也是為了告訴后來遇到同樣或者相似問題的小白吧,還請相關帖子管理人員別刪:在 Component.contextTypes這兒,我查到過有人把它以這種方式寫到過組件內(nèi)部:
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寫好了并且構造函數(shù)調(diào)用super是沒有把context弄丟
class Component { constructor(props, context) { super(...arguments) // 這樣才行,如果只寫props, 會把context 弄丟,所以super時始終建議這么寫 }}
相關文章:
1. dockerfile - [docker build image失敗- npm install]2. docker安裝后出現(xiàn)Cannot connect to the Docker daemon.3. docker gitlab 如何git clone?4. python - pandas按照列A和列B分組,將列C求平均數(shù),怎樣才能生成一個列A,B,C的dataframe5. 求一個mySQL安裝包6. docker-machine添加一個已有的docker主機問題7. 使用mysql自增主鍵遇到的問題8. css3 - [CSS] 動畫效果 3D翻轉bug9. java - Tomcat 不同的域名訪問同一個項目的不同網(wǎng)頁10. javascript - 文件改后綴后怎么獲得原來是什么類型的
