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),有點疑問了。。。代碼結(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(...)}
然而這么做我這兒始終出問題,就是報錯 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. javascript - sublime快鍵鍵問題2. javascript - immutable配合react提升性能?3. 配置Apache時,添加對PHP的支持時語法錯誤4. 實現(xiàn)bing搜索工具urlAPI提交5. javascript - vue-router 地址改變數(shù)據(jù)未改變6. javascript - html5多個label中其中一個觸發(fā)change,如何判斷是哪一個出發(fā)了change7. javascript - 移動端上不能實現(xiàn)拖拽布局嗎?8. css - 寫頁面遇到個布局問題,求大佬們幫解答,在線等,急!~9. phpstudy8.1支持win11系統(tǒng)嗎?10. javascript - nodejs關(guān)于進程間發(fā)送句柄的一點疑問

網(wǎng)公網(wǎng)安備