search

Home  >  Q&A  >  body text

javascript - Reactjs problem about jumping this.context.router.push(path) within a function

I’d like to ask my senior brothers for advice.
I created a component Component and wrote a jump function similar to this.context.router.push("/user/list") inside an ajax success callback. At the same time, Component.contextTypes={ router: React.PropTypes.object.isRequired } is written outside the component. The ajax request was also successful, but the page did not jump, which is a bit doubtful. . .
The code structure is similar:

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

reply all(3)I'll reply

  • 仅有的幸福

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

    Can’t get this?. Try using success()->()

    reply
    0
  • 阿神

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

    Here I will write about the pitfalls I encountered when searching for answers on the Internet. At the same time, it is also to inform novices who encounter the same or similar problems later. Please also ask the relevant post managers not to delete:
    In Component.contextTypes, I found it Someone wrote it inside the component this way:

    class Component extends React.Component{
        [有些人写static有些人又不写static] contentTypes: {
            router: React.PropTypes.object.isRequired
        }
        ...
        this.context.router.push(...)
    }

    However, when I do this, I always get a problem here, that is, the error "Cann't read the property 'push' is not defined" is reported. It’s not obvious why, let’s write it down first

    reply
    0
  • 曾经蜡笔没有小新

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

    "Cann't read the property 'push' is not defined"
    This error ensures that contextTypes is written
    and the constructor does not lose the context when calling super

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

    reply
    0
  • Cancelreply