【问题标题】:React "this" undefined in method child async func在方法子异步函数中反应“this”未定义
【发布时间】:2017-07-03 15:08:07
【问题描述】:

我有一个组件,我在其中定义了 handleClick(onClick 处理程序)并且我想调用 Async 函数。下面是我所做的代码,我的问题是:为什么在 Async function() 调用中无法访问“this”?

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

【问题讨论】:

  • 函数不使用this

标签: javascript reactjs ecmascript-2017


【解决方案1】:

解决了。我在 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);

【讨论】:

    猜你喜欢
    • 2017-07-15
    • 2017-05-20
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    • 2020-05-05
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多