无法在Modal React JS中为数据表传递参数

时间:2019-10-06 22:00:03

标签: reactjs datatable undefined modal-window

我有一个数据表,如果您选择一行,它会弹出一个模式窗口。我希望模式窗口仅显示所选行的数据表以及其他详细信息。但是,为模态窗口传递所选行的ID似乎不起作用,我不知道为什么?还是我不确定在模态窗口中显示信息的更好方法是什么?

**编辑:我发现如果我用t替换this.state.TicketID且t = 0,那么它也可以工作,因此它一定与在x []中调用this.state.TicketID有关吗?

        const {id, created} = t
      })
      return (
        <div>
        <Modal isOpen={this.state.modal} toggle={this.toggleModal} className={this.props.className}>
          <ModalHeader toggle={this.toggleModal}>Selected Item </ModalHeader>
          <ModalBody>
            <Datatable>
               <table className="table table-striped my-4 w-100">
                  <thead>
                     <tr>
                       <td>Ticket ID</td>
                       <td>Created On</td>
                     </tr>
                   </thead>
                   <tbody>
                     <tr key={this.state.TicketID}>
                       <td>{this.state.x[this.state.TicketID].id}</td>
                       <td>{this.state.x[this.state.TicketID].created}</td>
                     </tr>
                   </tbody>
                 </table>
              </Datatable>
          </ModalBody>
        </Modal>
      </div>
      );
    }

TicketID在外部函数中设置,并保留在状态对象中。它正在按预期更新。我注意到如果我执行console.log({this.state.x [0] .id}),那么它就可以工作。但是,如果我执行console.log({this.state.x [this.state.TicketID] .i​​d}),则会显示无法读取的属性“ id”,其状态为undefined。任何帮助或新建议将不胜感激!

1 个答案:

答案 0 :(得分:1)

实际上,对于当前用例,您甚至不需要模态级别状态,因此只需将模态组件设为纯组件(普通js函数),然后将值作为道具传递!

    // pass these form the parent components 
    const {isOpend , onToggle, ticket:{id,created} ={}}= props // or from `currentActiveTicket` as described below 
    // if you mounting the modal element on the same datatable level 
    // and you only change the state of the parent component
    // when a row is clicked you can add the `currentActiveTicket` as an object 
   // value of what you want to display on the modal(make sense)
  })
      return (
        <div>
        <Modal isOpen={isOpend} toggle={onToggle} className={this.props.className}>
          <ModalHeader toggle={this.toggleModal}>Selected Item </ModalHeader>
          <ModalBody>
            <Datatable>
               <table className="table table-striped my-4 w-100">
                  <thead>
                     <tr>
                       <td>Ticket ID</td>
                       <td>Created On</td>
                     </tr>
                   </thead>
                   <tbody>
                     <tr key={id}>
                       <td>{id}</td>
                       <td>{created}</td>
                     </tr>
                   </tbody>
                 </table>
              </Datatable>
          </ModalBody>
        </Modal>
      </div>
      );
    }

或者您必须保持道具变化并将其反映在模态上

  

例如,我之所以陷入此类问题是因为我对这些概念的理解不够充分-componentDidUpdate check the references on this