javascript - Reactjs關於函數內跳轉 this.context.router.push(path)的問題
PHP中文网
PHP中文网 2017-07-05 11:04:52
0
3
1052

請教各位師兄了。
我建立了一個元件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
}
PHP中文网
PHP中文网

认证0级讲师

全部回覆(3)
仅有的幸福

是不是拿不到this?. 試試用 success()->()

阿神

這裡寫一下在網上查找答案時遇到的坑,同時也是為了告訴後來遇到同樣或者相似問題的小白吧,還請相關帖子管理人員別刪:
在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。不太明顯為啥呢,先記下來再說吧

曾经蜡笔没有小新

"Cann't read the property 'push' is not defined"
這個錯誤確保contextTypes寫好了
並且構造函數調用super是沒有把context弄丟

class Component {
  constructor(props, context) {
    super(...arguments) // 这样才行,如果只写props, 会把context 弄丢,所以super时始终建议这么写
  }
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!