在reactjs中触发ajax成功的父函数

Den*_*nis 1 javascript jquery reactjs

如果您在 onClick 事件(或类似事件)上触发它,我知道如何让父函数运行,但我想在 ajax 成功时触发它。所以几乎这个星座:

var parent = React.createClass({
    someFunction: function(){
        console.log("Parent function triggered");
    },
    render: function(){
        return (
            <Child callback={this.someFunction} />
        );
    }
});

var child = React.createClass({
    getInitialState: function(){
        return { data: "Wat" };
    },
    componentDidMount: function(){
        $.ajax({
            url: "some_url",
            method: 'POST',
            data: this.state.data,
            success: function(response){
                this.props.callback; // This is what I would like to do
            },
            error: function(){
                console.log("Couldn't do it cap'n");
            }
        });
    },
    render: function(){
        return(
            <div>Hello!</div>
        );  
    }
});
Run Code Online (Sandbox Code Playgroud)

我可以通过触发一个事件来做到这一点,但是当我可以访问该功能时,当然应该可以做到这一点。该函数也被正确传递,如果我执行一个函数,我可以将其视为一个函数console.log(this.props.callback);

Buz*_*nas 5

您应该使用Function.prototype.bind来更改函数的this关键字:

success: function(response){
  this.props.callback(); // This will work
}.bind(this),
Run Code Online (Sandbox Code Playgroud)

最初,this您作为方法success选项传递的匿名函数内部的关键字与其外部的关键字不同。ajaxthis

发生这种情况是因为 Javascript 的词法作用域,您可以通过覆盖this调用函数时关键字的内容来更改此行为。


另一种选择是使用辅助变量,例如:

componentDidMount: function() {
  var self = this;
  $.ajax({
    /* (...) */
    success: function(response) {
      self.props.callback(); // this will work as well
    },
    /* (...) */
  });
}
Run Code Online (Sandbox Code Playgroud)

另一种选择是Kevin B的建议,使用 jQuery 的 AJAXcontext选项:

componentDidMount: function() {
  $.ajax({
    /* (...) */
    context: this,
    success: function(response) {
      this.props.callback(); // this will work as well
    },
    /* (...) */
  });
}
Run Code Online (Sandbox Code Playgroud)

最后一个选项,由于您使用的是 React,您可能正在通过 Babel 转译您的代码,因此,您可以利用ES6 的箭头函数,这将自动按词法进行this绑定:

success: (response) => {
  this.props.callback(); // This will work too
},
Run Code Online (Sandbox Code Playgroud)