我有一个构造函数,它注册一个事件处理程序:
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)
但它表现出同样的问题.
如何访问正确的对象?
我试图在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)
不确定是什么导致了这一点.如果有人指出我正确的方向,那将是非常有帮助的.提前致谢.