React JS中如何获取并展示对象数组的最后一个元素
解决方案
你不需要用map遍历整个数组(map会处理数组里每一个元素,这就是为什么会显示所有对象),直接获取数组的最后一项即可实现需求:
修改后的完整代码
import React, { Component } from 'react'; import axios from 'axios'; class ConfirmBooking extends Component { state = { bookings: [] } componentDidMount() { axios.get('http://localhost:5000/api') .then(res => { console.log(res.data) this.setState({ bookings: res.data }) }) .catch((error) => { console.log(error) }) } render() { // 直接获取数组最后一个对象 const lastBooking = this.state.bookings[this.state.bookings.length - 1]; return ( <div> {/* 加判断避免数组为空时报错 */} {lastBooking && ( <div key={lastBooking.id || 'last-booking'}> <h6>{`Name: ${lastBooking.name} Service: ${lastBooking.service} Date: ${lastBooking.date} Cost: ${lastBooking.cost}`}</h6> </div> )} </div> ) } } export default ConfirmBooking;
关键说明
- 获取最后一项:通过
数组.length - 1拿到最后一个元素的索引,直接取出对应对象;如果你的环境支持ES6,也可以用更简洁的this.state.bookings.at(-1)来获取 - 空值判断:添加
lastBooking && ...的逻辑,避免请求未完成、数组为空时出现报错 - key属性:给包裹的div添加合法key,优先用数据自带的唯一标识(比如
lastBooking.id),没有的话可以用固定字符串替代
内容的提问来源于stack exchange,提问作者Mercy Abolade
相关产品推荐
相关产品推荐

