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

如何用React创建可选择显示数量的API列表下拉框

实现下拉框选择数量并展示对应API数据列表

问题描述

我想要创建一个下拉框,可根据选择的数值显示对应数量的API数据列表。例如,选择30则显示1-30条数据,选择50则显示1-50条数据,请问该如何实现?

现有代码

const [data, setData] = useState([]);
const [id, setId]= useState('');
const [index, setIndex] = useState(10)

useEffect(() => {
  const loadData = async () => {
    await fetch(`https://swapi.dev/api/people/${id}/`)
    .then((response) => response.json())
    .then((ReceivedData) => setData(ReceivedData));
    }
loadData()
},[id]);

return(
 <select>
<option selected >10</option>
<option selected >50</option>
<option selected >60</option>
 </select> 
{data.map((datas,index){
        <table className="table">
     <tbody>
    <thead>
      <tr>
        <th scope="col">Name</th>
        <th scope="col">Height</th>
        <th scope="col">Mass</th>
        <th scope="col">Hair Color</th>
        <th scope="col">Eye Color</th>
      </tr>
    </thead>
    <tr key={index}>
        <th scope="row">{datas.name}</th>
        <td>{datas.height}</td>
        <td>{datas.mass}</td>
        <td>{datas.hair_color}</td>
        <td>{datas.eye_color}</td>
      </tr>
    </tbody>
  </table>)}
)

解决方案

你的现有代码存在接口调用逻辑、渲染结构的问题,以下是修正后的完整实现:

1. 核心逻辑调整

  • 改用SWAPI的列表接口/people/,通过limit参数指定返回数据数量(比如?limit=30返回前30条)
  • 绑定下拉框选择事件,同步选中数量到状态,触发数据重新加载
  • 修复表格渲染结构,避免重复生成整个表格

完整代码

import { useState, useEffect } from 'react';

function PeopleList() {
  const [data, setData] = useState([]);
  // 存储选中的显示数量,默认值设为10
  const [showCount, setShowCount] = useState(10);

  useEffect(() => {
    const loadData = async () => {
      try {
        const response = await fetch(`https://swapi.dev/api/people/?limit=${showCount}`);
        const receivedData = await response.json();
        // API返回的列表数据在results字段中
        setData(receivedData.results);
      } catch (error) {
        console.error('加载数据失败:', error);
      }
    };
    loadData();
  }, [showCount]); // 依赖showCount,数值变化时自动重新请求数据

  return (
    <div>
      {/* 下拉框绑定状态与选择事件 */}
      <select value={showCount} onChange={(e) => setShowCount(Number(e.target.value))}>
        <option value="10">10</option>
        <option value="30">30</option>
        <option value="50">50</option>
        <option value="60">60</option>
      </select>

      {/* 表格结构优化:表头只渲染一次,map仅生成数据行 */}
      <table className="table">
        <thead>
          <tr>
            <th scope="col">Name</th>
            <th scope="col">Height</th>
            <th scope="col">Mass</th>
            <th scope="col">Hair Color</th>
            <th scope="col">Eye Color</th>
          </tr>
        </thead>
        <tbody>
          {data.map((person, index) => (
            <tr key={index}>
              <th scope="row">{person.name}</th>
              <td>{person.height}</td>
              <td>{person.mass}</td>
              <td>{person.hair_color}</td>
              <td>{person.eye_color}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default PeopleList;

关键说明

  • 利用API自带的limit参数控制返回数量,是实现需求最直接的方式
  • 下拉框的value与showCount双向绑定,确保选中状态与数据同步
  • 表格结构调整后避免了重复渲染表头,提升性能的同时符合语义规范
  • 添加错误捕获处理,避免API请求失败导致页面异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 18:15:47