Heim  >  Fragen und Antworten  >  Hauptteil

javascript – ReactJS-Problem beim Springen von this.context.router.push(path) innerhalb der Funktion

Ich bitte Sie alle um Rat.
Ich habe eine Komponente Component erstellt und eine Sprungfunktion ähnlich this.context.router.push("/user/list") in einen Ajax-Erfolgsrückruf geschrieben. Gleichzeitig wird Component.contextTypes={ router: React.PropTypes.object.isRequired } außerhalb der Komponente geschrieben. Die Ajax-Anfrage war ebenfalls erfolgreich, aber die Seite ist nicht gesprungen, was etwas zweifelhaft ist. . .
Die Codestruktur ist ähnlich:

class Component extends React.Component{
    ...
    success: function(data) {
        alert(data);
        this.context.router.push(...)
    }
}
Component.contextTypes={
    router: React.PropTypes.object.isRequired
}
PHP中文网PHP中文网2663 Tage vor1054

Antworte allen(3)Ich werde antworten

  • 仅有的幸福

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

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

    Antwort
    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。不太明显为啥呢,先记下来再说吧

    Antwort
    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时始终建议这么写
      }
    }

    Antwort
    0
  • StornierenAntwort