简体   繁体   English

如何为数组 map 中的单个项目更新 state?

[英]How do I update the state for a single item in an array map?

Here's a snippet of my code.这是我的代码片段。 It generates a table with the option to sent an email invite to each person.它会生成一个表格,其中包含向每个人发送 email 邀请的选项。


constructor(props){
    super(props)

    this.state={
        persons:[],
        inviteSent: false,
    }
}

async componentDidMount(){
   this.setState({
      patients:this.props.patients,
   })
}

sendInvite = async (person) => {
        let response = ***code to send email invite***

        if(response.ok){
           this.setState({
              inviteSent: true,
           })
        }       
    }

let personList = this.props.personList
    
        let persons = personList.map((person, index)=>
            {
                return (
                    <tr key={index}>
                        <td> 
                           {!this.state.inviteSent &&
                              <div onClick={()=>this.sendInvite(person)}>Send Invite</div>
                           }
                           {this.state.inviteSent &&
                              <div>Email Sent</div>
                            }
                        </td>
                    </tr>
                )
             }

Basically, there's a button to send an email invite to each person in the table, and once sent, that specific button should disappear and be replaced by a confirmation that says 'Email Sent'.基本上,有一个按钮可以向表中的每个人发送 email 邀请,一旦发送,该特定按钮应该会消失并由“已发送电子邮件”的确认信息取代。 However, since the state of inviteSent isn't mapped to the particular person, it updates all the rows with 'Invite Sent'.但是,由于inviteSent 的inviteSent没有映射到特定的人,它会使用“Invite Sent”更新所有行。 How do I map it to that specific person?我如何 map 给那个特定的人?

You can add 'inviteSent' to every person (if it possible):您可以向每个人添加“inviteSent”(如果可能的话):

persons:[
  {person: 'name', inviteSent: true},
  {person: 'name', inviteSent: false},
],

You have to store the list of persons in the state, each having an own „inviteSent“ Attribute.您必须将人员列表存储在 state 中,每个人都有自己的“inviteSent”属性。 When an invite was sent to one person, you have to find the person in the list which shall be updated.当邀请发送给一个人时,您必须在列表中找到要更新的人。 This can be achieved for example using the array method „map“ which allows to iterate over an array to find the one item meeting a specific condition for example a person with a certain id.这可以例如使用数组方法“map”来实现,该方法允许遍历数组以找到满足特定条件的一个项目,例如具有特定 id 的人。

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

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