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

React记分板组件如何将初始默认状态设置为榜首队伍的分数

解决方案

你只需要调整TopGroups组件的逻辑,在接口数据加载完成后,将排序后的榜首队伍数据赋值给初始状态即可,具体修改如下:

核心修改点

  1. 修正loading状态缺少return的问题,避免加载阶段执行后续异常逻辑
  2. 把排序后的队伍数组提升到公共作用域,方便后续读取榜首数据
  3. 新增useEffect监听接口返回的data,数据加载完成后自动更新三个展示状态为榜首队伍的对应数值

修改后完整代码

const TopGroups = () => {
  const currentQTR = `Q${moment().quarter()} ${moment().year()}`;
  const { loading, error, data } = useQuery(GET_GROUP_SCORES, {
    variables: { quarter: currentQTR },
  });
  // 把排序后的数组提到外部作用域
  let sortedGroups = [];
  if (data) {
    sortedGroups = data.getGroupScores.sort((a, b) => {
      if (a.totalScore > b.totalScore) {
        return -1;
      }
      if (a.totalScore < b.totalScore) {
        return 1;
      } else {
        return 0;
      }
    });
  }
  if (error) {
    return <p>An error has occured</p>;
  }
  if (loading) {
    // 补上return 避免继续执行后面的逻辑
    return <Spinner />;
  }
  const [displayGoals, setDisplayGoals] = useState("0");
  const [displayPoints, setDisplayPoints] = useState("0");
  const [displayMilestones, setDisplayMilestones] = useState("0");
  // 新增useEffect 数据加载完成后自动赋值榜首数据
  useEffect(() => {
    if (sortedGroups.length > 0) {
      const topGroup = sortedGroups[0];
      setDisplayGoals(topGroup.goalsDone);
      setDisplayPoints(topGroup.totalScore);
      setDisplayMilestones(topGroup.milestonesDone);
    }
  }, [sortedGroups]);
  return (
    <div className="row-12">
      <TeamCard
        data={data}
        setDisplayGoals={setDisplayGoals}
        setDisplayPoints={setDisplayPoints}
        setDisplayMilestones={setDisplayMilestones}
      />
      {/* 你原来剩下的渲染逻辑 */}
    </div>
  );
};

如果需要做异常兜底,可以在赋值的时候加可选链和默认值,避免空数组报错:

setDisplayGoals(sortedGroups?.[0]?.goalsDone ?? "0");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:36:03