javascript - Reactjs關(guān)于函數(shù)內(nèi)跳轉(zhuǎn) this.context.router.push(path)的問(wèn)題
問(wèn)題描述
請(qǐng)教各位師兄了。我創(chuàng)建了一個(gè)組件Component,并在內(nèi)部中的一個(gè)ajax成功回調(diào)內(nèi),寫(xiě)了this.context.router.push('/user/list')類(lèi)似的跳轉(zhuǎn)功能。同時(shí)在組件外寫(xiě)了Component.contextTypes={ router: React.PropTypes.object.isRequired }。ajax也成功請(qǐng)求了,但是頁(yè)面并沒(méi)有跳轉(zhuǎn),有點(diǎn)疑問(wèn)了。。。代碼結(jié)構(gòu)類(lèi)似:
class Component extends React.Component{ ... success: function(data) {alert(data);this.context.router.push(...) }}Component.contextTypes={ router: React.PropTypes.object.isRequired}
問(wèn)題解答
回答1:是不是拿不到this?. 試試用 success()->()
回答2:這里寫(xiě)一下在網(wǎng)上查找答案時(shí)遇到的坑,同時(shí)也是為了告訴后來(lái)遇到同樣或者相似問(wèn)題的小白吧,還請(qǐng)相關(guān)帖子管理人員別刪:在 Component.contextTypes這兒,我查到過(guò)有人把它以這種方式寫(xiě)到過(guò)組件內(nèi)部:
class Component extends React.Component{ [有些人寫(xiě)static有些人又不寫(xiě)static] contentTypes: {router: React.PropTypes.object.isRequired } ... this.context.router.push(...)}
然而這么做我這兒始終出問(wèn)題,就是報(bào)錯(cuò) Cann’t read the property ’push’ is not defined。不太明顯為啥呢,先記下來(lái)再說(shuō)吧
回答3:'Cann’t read the property ’push’ is not defined'這個(gè)錯(cuò)誤確保contextTypes寫(xiě)好了并且構(gòu)造函數(shù)調(diào)用super是沒(méi)有把context弄丟
class Component { constructor(props, context) { super(...arguments) // 這樣才行,如果只寫(xiě)props, 會(huì)把context 弄丟,所以super時(shí)始終建議這么寫(xiě) }}
相關(guān)文章:
1. python bottle跑起來(lái)以后,定時(shí)執(zhí)行的任務(wù)為什么每次都重復(fù)(多)執(zhí)行一次?2. javascript - ios返回不執(zhí)行js怎么解決?3. javascript - vue2如何獲取v-model變量名4. node.js - vue中 post數(shù)據(jù)遇到問(wèn)題5. 前端 - 誰(shuí)來(lái)解釋下這兩個(gè) CSS selector 區(qū)別6. javascript - 求幫助 , ATOM不顯示界面!!!!7. html5 - HTML代碼中的文字亂碼是怎么回事?8. javascript - angular使從elastichearch中取出的文本高亮顯示,如圖所示9. mysql - 分庫(kù)分表、分區(qū)、讀寫(xiě)分離 這些都是用在什么場(chǎng)景下 ,會(huì)帶來(lái)哪些效率或者其他方面的好處10. python - 爬蟲(chóng)模擬登錄后,爬取csdn后臺(tái)文章列表遇到的問(wèn)題
