首頁  >  問答  >  主體

javascript - Reactjs關於函數內跳轉 this.context.router.push(path)的問題

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

全部回覆(3)我來回復

  • 仅有的幸福

    仅有的幸福2017-07-05 11:06:52

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

    回覆
    0
  • 阿神

    阿神2017-07-05 11:06:52

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

    回覆
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-07-05 11:06:52

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

    class Component {
      constructor(props, context) {
        super(...arguments) // 这样才行,如果只写props, 会把context 弄丢,所以super时始终建议这么写
      }
    }

    回覆
    0
  • 取消回覆