React Antd在array.map

时间:2018-11-21 02:09:55

标签: reactjs antd

单击更新按钮时,模式弹出两次,第一个显示正确的item.id,但是第二个是列表中的最后一个值。任何帮助表示赞赏。尝试在模式标记内添加{this.props.child},但无效。

任何帮助将不胜感激。

 this.state = {
  ModalText: 'Content of the modal',
  visible: false,
  currentId : 0,
  confirmLoading: false,
 }
}

showModal = () => {
 this.setState({
  visible: true,
 });
}



handleOk = () => {
    this.setState({
      ModalText: 'The modal will be closed after two seconds',
      confirmLoading: true,
    });
    setTimeout(() => {
      this.setState({
        visible: false,
        confirmLoading: false,
      });
    }, 2000);
  }

  handleCancel = () => {
    console.log('Clicked cancel button');
    this.setState({
      visible: false,
    });
  }

  render(){
    const { visible, confirmLoading, ModalText } = this.state;
    return(
      <div>
        <ul>
          {this.props.user.map(item => (
            <li key={item.id}>
              The person is {item.name} and the his/her email is 
 {item.email}.

            <Button type="primary" onClick={this.showModal}>
              Update
            </Button>
            <Modal title="Title"
              visible={visible}
              onOk={this.handleOk}
              confirmLoading={confirmLoading}
              onCancel={this.handleCancel}

            >
              {item.id}
              <UpdateModal/>

            </Modal>

            </li>
          ))}
        </ul>
        </div>
    )
  }
 }

2 个答案:

答案 0 :(得分:1)

我认为,如果您要通过开发人员工具查看DOM,您会发现模式不会弹出两次,而是每个项目弹出一次,并且显示最后一个项目的模式只是最上面的一个。在您的状态下,所有模态(每个项目渲染一个模态)都由相同的visible布尔值控制,因此通过单击列表中的任何按钮将其设置为true会显示所有模态。

有几种方法可以解决此问题。一种选择是在li之外具有单个模式,并在单击特定按钮时将项目ID设置为状态,然后在模式中使用该状态。

答案 1 :(得分:0)

模态出现多次的原因是

  1. 即使在您未单击组件时,呈现组件时也会自动调用按钮的this.showModal

  2. 您总是在不进行任何条件检查的情况下显示模式,因此您需要对模式进行条件检查

所以改变

     <Button type="primary" onClick={this.showModal}>
          Update
        </Button>
        <Modal title="Title"
          visible={visible}
          onOk={this.handleOk}
          confirmLoading={confirmLoading}
          onCancel={this.handleCancel}

        >
          {item.id}
          <UpdateModal/>

        </Modal>

收件人

     <Button type="primary" onClick={() => this.showModal()}> //made changes here
          Update
        </Button>
      //added change here —>  {visible && <Modal title="Title"
          visible={visible}
          onOk={this.handleOk}
          confirmLoading={confirmLoading}
          onCancel={this.handleCancel}

        >
          {item.id}
          <UpdateModal/>}

        </Modal>
相关问题