【问题标题】:React parent property function not firing when called from child function从子函数调用时反应父属性函数不触发
【发布时间】:2019-07-11 17:37:21
【问题描述】:

在我的父组件中,我有一个名为 handleDocumentSubmission 的函数,我想将它传递给子组件。

  handleDocumentSubmission = input => async (e) => {
       console.log("fired");

然后我像这样渲染以下组件。我使用相同的函数名。

  <FrontConfirm
                    nextStep={this.nextStep}
                    handleReview={this.handleReview}
                    values={values}
                    handleDocumentSubmission={this.handleDocumentSubmission}
                />

现在在我的子组件中,我想通过单击按钮从子函数调用此函数。

  continue = () => {
        console.log("clicked", this.props);
        this.props.handleDocumentSubmission("front");
    };

<Button onClick={this.continue}
  variant="contained" color="primary">
  Confirm
</Button>

现在,我可以通过具有我的 handleDocumentSubmission 功能的道具看到单击的控制台日志。但是父函数console.log("fired") 的console.log 没有被调用。

【问题讨论】:

  • 当您使用异步函数时,您应该在continue 方法中使用await this.props.handleDocumentSubmission("front");

标签: javascript reactjs ecmascript-6


【解决方案1】:

这是因为 handleDocumentSubmission 是一个接受 2 组参数的柯里化函数。通过使用以下语法并传递您的事件参数,它将起作用:

continue = ev => {
    console.log("clicked", this.props);
    this.props.handleDocumentSubmission("front")(ev);
};

你的函数也不需要是异步的:

handleDocumentSubmission = input => e => {
    console.log("fired");
}

没有continue 函数的最终语法(我假设您创建它是为了测试)将如下:

<Button onClick={this.props.handleDocumentSubmission("front")}
    variant="contained" color="primary">
    Confirm
</Button>

使用它,您的函数将在触发时接收您的值 (front) 和事件信息。


拥有一个同步函数不会阻止它返回一个值:

handleDocumentSubmission = input => e => {
    console.log("fired");
    return 'success'
}

continue = ev => {
    console.log("clicked", this.props);
    const result = this.props.handleDocumentSubmission("front")(ev);
    console.log(result)
};

如果您真的希望它是 async,请使用 await 关键字:

handleDocumentSubmission = input => async e => {
    console.log("fired");
    return /* A promise  */
}

continue = async ev => {
    console.log("clicked", this.props);
    const result = await this.props.handleDocumentSubmission("front")(ev);
    console.log(result)
};

【讨论】:

  • 对不起,我忘了提handleDocumentSubmission 需要是异步的,我想根据“handleDocumentSubmission”中发生的事情在conintue 函数中向子进程返回成功或失败信息。
  • 所以 continue 也将是异步的,因为它正在等待来自 handleDocumentSubmission 的响应。 handleDocumentSubmission 将执行异步调用并返回成功或失败响应,该响应应由 continue 读取。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多