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

如何用React+Axios获取JSONPlaceholder的前8条照片数据?

获取JSONPlaceholder前8张照片的React实现调整

嘿,很简单就能实现只获取前8张照片的需求,JSONPlaceholder API本身就支持通过查询参数限制返回结果数量,不用先拿全部数据再截取,这样更高效。

修改步骤:

  • 在Axios的请求URL中添加?_limit=8参数,API会直接返回前8条照片数据
  • 补充完整组件的state初始化和照片展示逻辑(原代码里缺少这部分,我帮你补上了)

修改后的完整代码:

class App extends React.Component {
  // 初始化state,包含加载状态、错误信息和照片数组
  state = {
    pictures: [],
    loading: true,
    error: null
  };

  componentDidMount() {
    // 添加?_limit=8参数,直接请求前8张照片
    axios.get(`https://jsonplaceholder.typicode.com/photos/?_limit=8`)
      .then(res => {
        const pictures = res.data;
        this.setState({ pictures, loading: false, error: null });
      })
      .catch(err => {
        this.setState({ loading: false, error: err });
      });
  }

  renderLoading() {
    return <div>Loading...</div>;
  }

  renderError() {
    return (
      <div>
        Something went wrong: {this.state.error.message}
      </div>
    );
  }

  // 新增展示照片的方法
  renderPictures() {
    return (
      <div className="photo-grid">
        {this.state.pictures.map(photo => (
          <div key={photo.id} className="photo-item">
            <img src={photo.thumbnailUrl} alt={photo.title} />
            <p>{photo.title}</p>
          </div>
        ))}
      </div>
    );
  }

  render() {
    const { loading, error } = this.state;

    // 根据状态渲染不同内容
    if (loading) return this.renderLoading();
    if (error) return this.renderError();

    return this.renderPictures();
  }
}

说明:

  1. API参数使用:_limit=8是JSONPlaceholder支持的内置参数,它会帮我们在服务端就限制返回的数据量,比客户端截取更节省带宽和内存
  2. 完整组件逻辑:补充了state的初始值,新增了renderPictures方法来展示照片列表,完善了render方法的状态判断逻辑
  3. key属性:在渲染列表时加上key={photo.id},符合React的列表渲染规范,避免警告

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:20:55