[英]How to modify a specific component of a list of component rendered using map in react?
[英]React: How to send specific data to a specific instance of a component created with .map
我正在从父组件中创建子组件的多个实例,如下所示:
render() {
return (
{this.state.accounts.map(account =>
<EachAccount key={account.id} curAccountData={account} />
)}
)
}
创建EachAccount组件时,会分别为每个组件提供唯一的数据,这些数据可以正常工作,并且EachAccount组件的每个状态都是唯一的。
但是我想将数据创建后仅将其传递给这些实例之一。
在创建数据后,我尝试将数据传递给EachAccount组件,但是不幸的是,每个实例都获取了数据,因此每个实例的状态都已更新。
有人知道解决方案吗?
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()}
)
}
}
我发现的最佳解决方案是将带有要更新的子ID的数据作为道具发送给每个实例,然后在该子内部创建一个条件,该条件仅在当前子ID和当前子ID为发送数据ID匹配。
这样的事情将在EachAccount组件中:
componentWillReceiveProps(nextProps) {
if(nextProps.updateBalanceFromId === this.state.curAccountData.id){
this.getBalances(nextProps.updateBalanceFromId)
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.