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

如何在React中对REST API返回数据按字母排序后再执行map?

如何在React中对API返回的数据按字母排序后渲染

我编写了用于获取API响应的React代码,现在需要将返回的数据按字母排序后再进行渲染:

原代码

import React, { useEffect, useState } from 'react'

function DataList( props ) {

    const [isLoading, setIsLoading] = useState(false);
    const [objData, setObjData] = useState({});

    useEffect( ()=>{
        setIsLoading(true);
        fetch("https://dummyjson.com/product")
        .then(res => res.json())
        .then((json)=>{
            setObjData(json);
            setIsLoading(false);
        })
    }, [] );
    console.log(objData);

  return (
    <div>
        <h1><u><i>Data List</i></u></h1>
        
        <table border="1" cellPadding={5} width={500}>
            <thead>
                <tr>
                    <th>Title</th>
                    <th>Brand</th>
                    <th>Price</th>
                    <th>Thumbnail</th>
                </tr>
            </thead>
            
            <tbody>
            <tr>
                <td colSpan={4}>{isLoading ? <p>Loading...</p> : null}</td>
            </tr>
                {
                    objData['products']?.map((product) => {
                        return <tr key={product.id}>
                            <td>{product.title}</td>
                            <td>{product.brand}</td>
                            <td>{product.price}</td>
                            <td align='center'>
                                <img src={product.thumbnail} alt={product.title} width={100} />
                            </td>
                        </tr>
                    })
                }

            </tbody>
        </table>
    </div>
  )
}

export default DataList

修改方案:按字母排序后渲染

我们可以在获取到API数据后,对products数组按标题(或品牌)进行字母排序,再更新状态。注意先拷贝数组,避免原地修改原数据:

import React, { useEffect, useState } from 'react'

function DataList( props ) {

    const [isLoading, setIsLoading] = useState(false);
    const [objData, setObjData] = useState({});

    useEffect( ()=>{
        setIsLoading(true);
        fetch("https://dummyjson.com/product")
        .then(res => res.json())
        .then((json)=>{
            // 对products数组按title字母升序排序
            const sortedProducts = json.products?.slice().sort((a, b) => {
                return a.title.localeCompare(b.title);
            });
            // 更新状态为排序后的数据
            setObjData({...json, products: sortedProducts});
            setIsLoading(false);
        })
    }, [] );

  return (
    <div>
        <h1><u><i>Data List</i></u></h1>
        
        <table border="1" cellPadding={5} width={500}>
            <thead>
                <tr>
                    <th>Title</th>
                    <th>Brand</th>
                    <th>Price</th>
                    <th>Thumbnail</th>
                </tr>
            </thead>
            
            <tbody>
                {isLoading ? (
                    <tr>
                        <td colSpan={4}><p>Loading...</p></td>
                    </tr>
                ) : (
                    objData['products']?.map((product) => {
                        return <tr key={product.id}>
                            <td>{product.title}</td>
                            <td>{product.brand}</td>
                            <td>{product.price}</td>
                            <td align='center'>
                                <img src={product.thumbnail} alt={product.title} width={100} />
                            </td>
                        </tr>
                    })
                )}
            </tbody>
        </table>
    </div>
  )
}

export default DataList

关键说明

  • 使用slice()创建数组副本,避免sort()原地修改原API返回的数据
  • localeCompare()方法用于字符串的字母排序,支持多语言,比直接用a.title > b.title更可靠
  • 如果需要按品牌(brand)排序,只需将a.title.localeCompare(b.title)改为a.brand.localeCompare(b.brand)即可
  • 优化了渲染逻辑,将loading状态和列表渲染用三元表达式整合,代码更简洁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 09:33:20