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

React使用Axios调用API返回空JSON对象时如何正确提示无数据

问题根因

你当前的判断逻辑失效核心是JavaScript类型判断的规则问题:空数组[]在JS中属于真值,![]的运算结果为false,加上你初始化时就给orders赋值为空数组,this.state.orders永远不会为undefined或null,所以!this.state.orders的判断永远不会触发,无数据提示自然不会显示。

同时你当前的show函数仅在无数据时有返回值,有数据时无返回内容,接口有数据时页面也会是空的,需要同步补充逻辑。

修复方案

基础修复(仅解决无数据提示失效)

直接修改判断条件为判断数组长度即可,同时兼容接口返回null/undefined的异常情况:

const show = () => {
  // 同时兼容值为空、值为 empty 数组的情况
  if(!this.state.orders || this.state.orders.length === 0) {
    return <>No orders</>;
  }
  // 补充有数据时的订单列表渲染逻辑,示例如下,按实际字段调整即可
  return this.state.orders.map(order => (
    <div key={order.id}>
      订单号:{order.orderNo} 金额:{order.amount}
    </div>
  ))
}

优化方案(增加加载态避免误导)

当前代码在接口请求过程中会直接显示无数据提示,容易误导用户,可以补充加载状态处理:

  1. 首先在state中新增加载状态标识:
state = {
  orders : [],
  loading: true // 新增加载状态,默认请求中
}
  1. 请求完成时关闭加载状态:
componentDidMount() {
  axios.get(`http://localhost:8080/api/order/findOrdersByUsername/12345`)
    .then(res => {
      const orders = res.data;
      this.setState( { orders, loading: false });
    })
    .catch(err => {
      // 错误场景也关闭加载状态,可按需补充错误提示
      this.setState({ loading: false })
    })
}
  1. 渲染逻辑优先判断加载状态:
const show = () => {
  if(this.state.loading) return <>订单加载中...</>
  if(!this.state.orders || this.state.orders.length === 0) {
    return <>No orders</>;
  }
  return this.state.orders.map(order => (
    <div key={order.id}>
      订单号:{order.orderNo} 金额:{order.amount}
    </div>
  ))
}

内容的提问来源于stack exchange,提问作者ucoder21

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 21:18:00