相关疑难解决方法(0)

如何在回调中访问正确的`this`?

我有一个构造函数,它注册一个事件处理程序:

function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', function () {
        alert(this.data);
    });
}

// Mock transport object
var transport = {
    on: function(event, callback) {
        setTimeout(callback, 1000);
    }
};

// called as
var obj = new MyConstructor('foo', transport);
Run Code Online (Sandbox Code Playgroud)

但是,我无法data在回调中访问已创建对象的属性.它看起来this并不是指创建的对象,而是指另一个对象.

我还尝试使用对象方法而不是匿名函数:

function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', this.alert);
}

MyConstructor.prototype.alert = function() {
    alert(this.name);
};
Run Code Online (Sandbox Code Playgroud)

但它表现出同样的问题.

如何访问正确的对象?

javascript callback this

1309
推荐指数
12
解决办法
36万
查看次数

TypeError:无法读取未定义的属性"setState"

我试图在ajax回调从REST api接收数据后设置组件的状态.这是我的组件构造函数的代码

constructor(props) {
    super(props);
    this.state = { posts: [] };
    this.getPosts = this.getPosts.bind(this);
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个componentDidMount看起来像下面的方法.

componentDidMount() {
        this.getPosts();
}
Run Code Online (Sandbox Code Playgroud)

现在这是我的getPosts函数,我正在执行ajax请求.

getPosts = () =>  {
    $.ajax({
        type: 'get',
        url: urlname,
        success: function(data) {
            this.setState( { posts: data } )
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

我想要设置状态,但我收到以下错误.

this.setState is not a function
Run Code Online (Sandbox Code Playgroud)

不确定是什么导致了这一点.如果有人指出我正确的方向,那将是非常有帮助的.提前致谢.

javascript ajax jquery this reactjs

3
推荐指数
1
解决办法
3421
查看次数

标签 统计

javascript ×2

this ×2

ajax ×1

callback ×1

jquery ×1

reactjs ×1