You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 19:35:22