javascript - 在reactjs中ajax成功触发父函数

标签 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>
        );  
    }
});

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

,我可以将其视为一个函数

最佳答案

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

success: function(response){
  this.props.callback(); // This will work
}.bind(this),

最初,您作为 success 选项传递给 ajax 方法的匿名函数中的 this 关键字是不一样的 this 在它外面。

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


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

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

还有一个选项是 Kevin B的建议,使用 jQuery 的 AJAX context 选项:

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

最后一个选项,由于您使用的是 React,您可能正在通过 Babel 转译代码,因此,您可以利用 ES6's arrow functions ,这将自动在词法上与 this 绑定(bind):

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

关于javascript - 在reactjs中ajax成功触发父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32995382/

相关文章:

javascript - Three.js Webgl 纹理错误 - 2 的幂 - 没有视频

javascript - React/Redux 无法迭代状态数组

javascript - 触发了错误的类

javascript - 有没有办法在 document.ready 上加载 doubleclick.net 广告代码?

javascript - 为什么 Blob of Array 比 Blob of Uint8Array 小?

javascript - 在行按钮单击上生成事件并添加图标?如何

javascript - 如何删除类并添加另一个类jquery

javascript - 在 Jquery 上解析 JSON

javascript - Python Selenium 中的 Firefox : driver.execute_script 尝试使用 JQuery 删除文本字符给出 "SecurityError: The operation is insecure"

android - React Native - 共享和重用组件