假设我已经安装了一个名为 something 的第三方反应组件库,它通过 onRequestName prop 调用给它的 async 函数 .

something 将使用异步函数中已解析的数据来呈现结果 .

<Something onRequestName={this.asyncFunction}/>

我的 async 函数 requires 用户输入,我想在用户提供输入时解析它 only (否则我应该拒绝承诺) .

asyncFunction = async () => {
  // get user input and then resolve this funciton
}

How should I proceed in this situation?

我发现讨论类似情况的唯一来源是this,它根本不关心反应 .

我不知道任何其他解决此问题的stackoverflow问题 . 如果您了解它,请告诉我 .


目前我正在做这样的事情(看起来很疯狂):

// my async function sets a resolve in State of the component
asyncFunction = () => {
  return new Promise((res, rej) => {
    this.setState({resolve: res, reject: rej, showForm: true})
  };
}

然后我调用 resolve ,它在用户提供输入时处于状态:

// resolve promise on user input

    {showForm &&
      <form 
         onSubmit={() => {
          this.state.resolve(this.state.userInput) // <-- resolve is called here
          this.setState({showForm: false})
         }}
      >
        <label>
          Name:
          <input 
            type="text" 
            value={this.state.value} 
            onChange={e => this.setState({userInput: e.target.value})} 
          />
        </label>
        <input type="submit" value="Submit" />
      </form>
    }