处理来自映射数组的React Child

时间:2018-09-28 13:58:28

标签: javascript reactjs

我在表中有行,我有一个从数组渲染的按钮。 (为简洁起见,我将整行排除在外)

  onDeleteAttachment = async (event, file) => {
    try {
        await this.props.deleteAttachment(file.Url);
        //Success now remove the row from the table
        var qualification = this.state.currentQualification;
        qualification._Attachments = qualification._Attachments.filter(a=> a != file);
        this.setState({currentQualification: qualification});
    }
    catch(ex){
        //Failed, I need to turn off the loader on the button
    }
  }


  render{
   return myArray.map(button => <DeleteButton onClick={onDeleteAttachment}>click me</DeleteButton>)
  }

单击该按钮时将显示一个加载程序。 DeleteButton的呈现方式如下:

   onClick(event){
      this.setState({loading: ture}); //This makes button turn into loader
       this.props.onClick(event); //push onchange to parent
   }

   render(){
       return 
    <Button onClick={onClick}>{this.state.loading ? "Loading" : "click me" </button>
   }

我遇到的问题是,我无法告诉孩子DeleteButton关闭装载机吗?

1 个答案:

答案 0 :(得分:0)

删除try-catch并让onDeleteAttachment抛出错误(或在捕获并处理错误后重新抛出错误):

onDeleteAttachment = async (event, file) => {
    await this.props.deleteAttachment(file.Url);
    //Success now remove the row from the table
    var qualification = this.state.currentQualification;
    qualification._Attachments = qualification._Attachments.filter(a=> a != file);
    this.setState({currentQualification: qualification});
}

并将try-catch添加到DeleteButton的{​​{1}}方法中,以便它可以捕获未处理的异常并管理其自身的状态。

onClick