Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React-prop函数中的prop函数_Javascript_Reactjs - Fatal编程技术网

Javascript React-prop函数中的prop函数

Javascript React-prop函数中的prop函数,javascript,reactjs,Javascript,Reactjs,我正在尝试为我的一个组件在另一个道具中执行道具。基本上,我必须等待一些数据从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.

我正在尝试为我的一个组件在另一个道具中执行道具。基本上,我必须等待一些数据从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()

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

如前所述,您实际上并没有调用该函数。但看起来您也没有考虑代码的异步性质,这也是一个问题

调用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);

您是否错过了方法getReportData调用this.getReportData()?你能写一个完整的组件吗?这样我就可以给你一个答案,提醒你在当前执行的块完成后状态会发生变化。您将无法访问
getReportData
中的新
this.state.reportId
。是的,我在函数的成功部分进行了回调,但我不知道setState中的第二个可选回调,所以我将使用它!原来的问题是缺少()太好了!很高兴我能帮忙。