简体   繁体   中英

React.js Props - Return specific property from array of objects

I'm a newbie of both js and react. I'm having a problem when try to render single property from array of objects. for example; how can i show last notification's text only.

function Navbar(props){
  return <>
  <div>Welcome {props.user.first_name} {props.user.last_name}</div>
  <p>You've got {props.notifications.length} notifications</p>
  <p>Your last notification is: {}</p>
  </>
}

let notifications = [{
  id: 1,
  text: "delivered"
}, {
  id:2,
  text:"received"
}]

const user = {
  first_name: "Gavin",
  last_name: "Belson"
}

const root = document.querySelector("#root")
render(<Navbar notifications={notifications} user={user} />, root);```

JS indexes start at 0. So to access an array's last element, you would need to subtract one from its length and then access it by passing the result to the brackets (you can also subtract it directly in the brackets). For example, you have this array:

const array = [1, 2, 3, 4, 5]

Its last element's index is 4 because the first element's is 0, but the length is 5. That's why you need to do that subtraction.

In your case, after subtracting, the returned value is an object which has the text property that you can access using the dot notation.

<p>Your last notification is: {props.notifications[props.notifications.length - 1].text}</p>

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