React.js Props:从对象数组中提取指定属性完成渲染
React渲染数组最后一个对象属性的实现方案
问题场景
在编写React组件时,需要从props传入的notifications对象数组中,取出最后一条通知的text属性渲染到页面,原有代码中最后一个p标签的插值表达式未填写正确取值逻辑。
原有待修正代码段:
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);
正确写法
JavaScript数组下标从0开始计数,数组最后一位元素的下标为数组长度 - 1,直接在花括号内按下标取到对应元素后访问text属性即可,修正后的最后一个p标签代码如下:
<p>Your last notification is: {props.notifications[props.notifications.length - 1].text}</p>
边界兼容优化
如果业务中存在notifications为空数组的情况,上述写法会尝试读取undefined的text属性从而抛出js报错,可以使用可选链操作符做空值兼容,空数组时该位置不会报错,会渲染为空内容:
<p>Your last notification is: {props.notifications?.[props.notifications.length - 1]?.text}</p>
修正后页面最终渲染结果:
- Welcome Gavin Belson
- You've got 2 notifications
- Your last notification is: received
内容的提问来源于stack exchange,提问作者plastik
相关产品推荐
相关产品推荐

