简体   繁体   English

ReactJS - 如何使用 id 从数组中渲染单个 object?

[英]ReactJS - How to render single object from an array using id?

In react app, I am trying to get single row from an array using id but it doesn't work.在反应应用程序中,我试图使用 id 从数组中获取单行,但它不起作用。

const result = [
 {id: 0, important: false, name: "Shruthi R", phone: "9834233433", email: "shruthi@gmail.com", work: "NicheSoft", city: "Mysore"},
 {id: 1, important: false, name: "Shivay", phone: "9442233166", email: "shivay@yopmail.com", work: "MicroSoft", city: "Mumbai"},
 {id: 2, important: false, name: "Yash Sindhya", phone: "7455454354", email: "yash@yopmail.com", work: "AirVoice", city: "Pune"},
 {id: 3, important: false, name: "Rajat", phone: "8456546555", email: "rajat@gmail.com", work: "Airtel", city: "Delhi"},
 {id: 5, important: false, name: "Surya S", phone: "9956546546", email: "surya@gmail.com", work: "Vodafone", city: "Chennai"},
 {id: 6, important: false, name: "Paridhi", phone: "8856544422", email: "paridhi@gmail.com", work: "MicroTech", city: "Lucknow"},
];

My onEditClick function is as shown below, here I want single(matching) row from an result using id我的onEditClick function 如下所示,这里我想要使用idresult中的单个(匹配)行

onEditClick = (event) => {
  console.log(event.target.id);
}

Provided event.target.id contains the relevant ID, you can use array method find() :如果event.target.id包含相关 ID,您可以使用数组方法find()

onEditClick = (event) => {
  const clickedResult = result.find(({id})=>id===parseInt(event.target.id));
  console.log('clickedResult', clickedResult);
}

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

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