【问题标题】:How do I update the state for a single item in an array map?如何更新数组映射中单个项目的状态?
【发布时间】:2020-11-01 21:52:29
【问题描述】:

这是我的代码的 sn-p。它会生成一个表格,其中包含向每个人发送电子邮件邀请的选项。


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>
                )
             }

基本上,有一个按钮可以向表格中的每个人发送电子邮件邀请,一旦发送,该特定按钮应该会消失,并由“电子邮件已发送”的确认信息取代。但是,由于inviteSent 的状态没有映射到特定的人,它会使用“邀请已发送”更新所有行。我如何将它映射到那个特定的人?

【问题讨论】:

  • 我看不到任何简单的解决方案,除了每个人都有一个名为“inviteSent”的新属性

标签: javascript reactjs mapping state


【解决方案1】:

您可以向每个人添加“inviteSent”(如果可能的话):

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

【讨论】:

  • 我觉得我做不到,每个人都已经有一堆道具了。 (例如名字、姓氏、电子邮件、电话等)
  • @Taco 这应该不是问题,你可以拥有任意数量的道具
  • 您可以将状态中的 'inviteSent' 更改为数组,并用被邀请人的 id 填充它(我希望每个人都有 id)inviteSent: [1, 3, 7]//邀请此 id 的人
  • @WillBlack 我不关注,我会在哪里设置?
  • @Taco 您目前在哪里阅读您的清单? IE。 this.props.personList
【解决方案2】:

您必须存储状态中的人员列表,每个人都有自己的“inviteSent”属性。当邀请发送给一个人时,您必须在列表中找到要更新的人。这可以例如使用数组方法“map”来实现,它允许遍历数组以找到满足特定条件的一项,例如具有特定 id 的人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    相关资源
    最近更新 更多