React "this" 在方法子异步函数中未定义
React "this" undefined in method child async func
我有一个组件,我在其中定义了 handleClick(onClick 处理程序)并且我想调用 Async 函数。下面是我所做的代码,我的问题:为什么 'this' 在 Async function() 调用中不可访问?
class GameListItem extends BaseComponent {
constructor(props, context) {
super(props, context);
this.state = {
name: props.name,
owner: props.owner,
uid: props.uid,
status: props.status
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
let inst = this;
(
async function() {
// WHY HERE 'this' is undefined?
let res = await inst.engine.async_action({'action': 'join_game', 'data': {'game_uid': inst.state.uid}});
console.log('res: ', res);
}()
);
}
render() {
return (
<li className="list-group-item" >
<ProtectedLink text={this.state.name} classes="game_link" onClick={this.handleClick}/>
</li>
);
}
}
已解决。我在 IIFE 中丢失了上下文。这有效:
(
async function(inst) {
let res = await inst.engine.async_action({'action': 'join_game', 'data': {'game_uid': inst.state.uid}});
console.log('res: ', res);
}
)(this);
我有一个组件,我在其中定义了 handleClick(onClick 处理程序)并且我想调用 Async 函数。下面是我所做的代码,我的问题:为什么 'this' 在 Async function() 调用中不可访问?
class GameListItem extends BaseComponent {
constructor(props, context) {
super(props, context);
this.state = {
name: props.name,
owner: props.owner,
uid: props.uid,
status: props.status
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
let inst = this;
(
async function() {
// WHY HERE 'this' is undefined?
let res = await inst.engine.async_action({'action': 'join_game', 'data': {'game_uid': inst.state.uid}});
console.log('res: ', res);
}()
);
}
render() {
return (
<li className="list-group-item" >
<ProtectedLink text={this.state.name} classes="game_link" onClick={this.handleClick}/>
</li>
);
}
}
已解决。我在 IIFE 中丢失了上下文。这有效:
(
async function(inst) {
let res = await inst.engine.async_action({'action': 'join_game', 'data': {'game_uid': inst.state.uid}});
console.log('res: ', res);
}
)(this);