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

React项目点击排序按钮后按相反字段排序问题排查

问题核心原因

  1. 原地修改props数组:Array.sort()是原地排序方法,你直接修改父组件传入的articles属性,会改变原始数组,后续每次排序都是在上一次修改后的数组基础上执行,直接导致排序逻辑错乱。
  2. 依赖项不全:useEffect的依赖数组只写了sortType,遗漏了articles,如果后续articles属性发生变化不会触发重新排序。
  3. 比较函数写法不严谨:用三目运算符判断大小返回1/-1的写法容易出错,日期直接做字符串比较也存在潜在兼容问题。

修正方案

直接替换Articles.js的代码即可,修改点如下:

  • 每次排序前先拷贝原始articles数组,避免修改原属性
  • 优化排序比较函数,数字直接做差,日期转时间戳做差实现降序
  • 补全useEffect的依赖项
import React, { useEffect, useState } from 'react';

function Articles({articles, sortType}) {
    
    const [ myArticles , setMyArticles] = useState([]);

    useEffect(()=>{
        // 先拷贝数组,避免修改原props
        const sortedArticles = [...articles];
        if (sortType === "date") {
            // 日期转时间戳降序,最新的在前
            sortedArticles.sort((a, b) => new Date(b.date) - new Date(a.date));
        } else {
            // 点赞数降序,最多的在前
            sortedArticles.sort((a, b) => b.upvotes - a.upvotes);
        }
        setMyArticles(sortedArticles);
    },[sortType, articles]) // 补全依赖项

    return (
        <div className="card w-50 mx-auto">
            <table>
                <thead>
                <tr>
                    <th>Title</th>
                    <th>Upvotes</th>
                    <th>Date</th>
                </tr>
                </thead>
                <tbody>
                {myArticles.map((myArticle,i)=>
                <tr data-testid="article" key={i}>
                    <td data-testid="article-title">{myArticle.title}</td>
                    <td data-testid="article-upvotes">{myArticle.upvotes}</td>
                    <td data-testid="article-date">{myArticle.date}</td>
                </tr>)}
                </tbody>
            </table>
        </div>
    );

}

export default Articles;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:57:03