简体   繁体   中英

React: How to send specific data to a specific instance of a component created with .map

I am creating multiple instances of a child component from a parent component like this:

render() {
    return (
        {this.state.accounts.map(account => 
            <EachAccount key={account.id} curAccountData={account} /> 
        )}
    )
}

When the EachAccount components are created they are each given unique data which works fine and each State of EachAccount component is unique.

But I want to pass data to just one of these instances AFTER they have already been created.

I tried passing data to the EachAccount component after it had already been created but unfortunately every instance got the data and therefore the state of every one of the instances got updated.

Anyone know a solution to this?

class YourComponent extends Component {
    renderAccounts(){
      return this.state.accounts.map(account => {
         if(certainCondition){
           // return Each Account with extra data
         }

         return (
           <EachAccount key={account.id} curAccountData={account} />

      })
    }

    render(){
     return (
       {this.renderAccounts()}
     )
    }

}

Best solution I found is to send the data with the ID of the child that you would like to update as a prop to every instance, and then inside of the child make a conditional that will only update the state if the current child ID and the send data ID match.

Something like this would be in the EachAccount component:

componentWillReceiveProps(nextProps) {
     if(nextProps.updateBalanceFromId === this.state.curAccountData.id){
         this.getBalances(nextProps.updateBalanceFromId)
     }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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