繁体   English   中英

prop函数中的React - prop函数

[英]React - prop function within prop function

我正试图在我的一个组件的另一个道具中执行道具。 基本上我必须等待一些数据从API返回,然后我想执行下一个道具。 这是我的组件2道具代码:

getReportId = () => {

// here I make a call to the API to get a unique report ID
// then I set the state of my component to the ID's value and try call the next function

this.setState({
    reportID: reportID
});

//here is where im trying to move onto the next part  but its not firing
this.getReportData;

}

getReportData = () => {
// here would be part 2 where I would get the data based off the report ID but its not firing..
}

不确定这是否是React开始时的正确方法? 如果是这样,那么不确定为什么道具没有开火......

你的函数没有被触发的原因是因为你没有调用它。

使用this.getReportData();

我不确定你是否在正确的轨道上,我必须看到整个组件。

正如Sven ten Haaf指出的那样,你实际上并没有调用这个功能。 但看起来你没有考虑代码的异步性质,这也是一个问题。

调用API意味着您的其余逻辑需要等到该API响应了剩余步骤所需的数据。

你没有说你是如何调用这个API的,但是如果我用jQuery进行AJAX调用,我会怎么做:

getReportId = () => {
  jQuery.ajax({
    type: "POST",
    url: "/myApi/someFunction",
    data : inputData,
    success: (data) => {
      this.setState({
        reportID: data.reportID
      }, () => {
        this.getReportData();  //this is the setState callback
      });
    }
  });   
}

getReportData = () => {
  ...
}

如果您不熟悉setState()回调,请查看此处的官方文档。

第二个参数是一个可选的回调函数,它将在setState完成并重新呈现组件后执行。

 setState(nextState, callback); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM