javascript - Reactjs關(guān)于函數(shù)內(nèi)跳轉(zhuǎn) this.context.router.push(path)的問題
問題描述
請教各位師兄了。我創(chuàng)建了一個組件Component,并在內(nèi)部中的一個ajax成功回調(diào)內(nèi),寫了this.context.router.push('/user/list')類似的跳轉(zhuǎn)功能。同時在組件外寫了Component.contextTypes={ router: React.PropTypes.object.isRequired }。ajax也成功請求了,但是頁面并沒有跳轉(zhuǎn),有點(diǎn)疑問了。。。代碼結(jié)構(gòu)類似:
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)上查找答案時遇到的坑,同時也是為了告訴后來遇到同樣或者相似問題的小白吧,還請相關(guān)帖子管理人員別刪:在 Component.contextTypes這兒,我查到過有人把它以這種方式寫到過組件內(nèi)部:
class Component extends React.Component{ [有些人寫static有些人又不寫static] contentTypes: {router: React.PropTypes.object.isRequired } ... this.context.router.push(...)}
然而這么做我這兒始終出問題,就是報(bào)錯 Cann’t read the property ’push’ is not defined。不太明顯為啥呢,先記下來再說吧
回答3:'Cann’t read the property ’push’ is not defined'這個錯誤確保contextTypes寫好了并且構(gòu)造函數(shù)調(diào)用super是沒有把context弄丟
class Component { constructor(props, context) { super(...arguments) // 這樣才行,如果只寫props, 會把context 弄丟,所以super時始終建議這么寫 }}
相關(guān)文章:
1. objective-c - ios百度地圖定位問題2. html - css 如何添加這種邊框?3. javascript - 求助這種功能有什么好點(diǎn)的插件?4. html5 - 如何解決bootstrap打開模態(tài)modal窗口引起頁面抖動?5. javascript - 求助關(guān)于js正則問題6. javascript - node.js服務(wù)端渲染解疑7. html5 - rudy編譯sass的時候有中文報(bào)錯8. javascript - 關(guān)于定時器 與 防止連續(xù)點(diǎn)擊 問題9. 為何 localStorage、sessionStorage 屬于html5的范疇,但是為何 IE8卻支持?10. 微信開放平臺 - Android調(diào)用微信分享不顯示
