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

如何在过滤API赛事数据后自动滚动至未开始赛事区域

React实现篮球赛事列表自动定位到未开始赛事

核心思路

先将赛事数据按状态分组(已结束FT在上,未开始NS在下),页面加载完成后自动滚动到第一个未开始赛事的位置,模拟西甲赛事页面的滚动定位效果。

实现步骤

1. 数据分组处理

获取API数据后,将赛事拆分为已结束和未开始两组,合并时保持已结束组在前:

import { useState, useEffect, useRef } from 'react';

function BasketballMatches() {
  const [filteredMatches, setFilteredMatches] = useState({ finished: [], upcoming: [] });
  const firstUpcomingRef = useRef(null);

  useEffect(() => {
    // 替换为实际API调用
    fetch('/api/basketball-matches')
      .then(res => res.json())
      .then(rawData => {
        const finishedMatches = rawData.filter(match => match.status === 'FT');
        const upcomingMatches = rawData.filter(match => match.status === 'NS');
        setFilteredMatches({ finished: finishedMatches, upcoming: upcomingMatches });
      });
  }, []);

2. 渲染分组赛事并标记定位目标

给第一个未开始赛事添加ref,作为滚动定位的目标元素:

return (
    <div className="matches-wrapper">
      {/* 已结束赛事区块 */}
      <section className="finished-section">
        <h2>已结束赛事</h2>
        {filteredMatches.finished.map(match => (
          <div key={match.id} className="match-item">
            <span>{match.homeTeam} {match.homeScore} - {match.awayScore} {match.awayTeam}</span>
            <span className="status">已结束</span>
          </div>
        ))}
      </section>

      {/* 未开始赛事区块 */}
      <section className="upcoming-section">
        <h2>未开始赛事</h2>
        {filteredMatches.upcoming.map((match, idx) => (
          <div
            key={match.id}
            className="match-item"
            ref={idx === 0 ? firstUpcomingRef : null}
          >
            <span>{match.homeTeam} vs {match.awayTeam}</span>
            <span className="status">{match.matchTime}</span>
          </div>
        ))}
      </section>
    </div>
  );

3. 页面加载后自动滚动

利用useEffect监听未开始赛事数据,当数据就绪且存在时,调用scrollIntoView完成定位:

useEffect(() => {
    // 仅当存在未开始赛事时执行滚动
    if (filteredMatches.upcoming.length > 0 && firstUpcomingRef.current) {
      firstUpcomingRef.current.scrollIntoView({
        behavior: 'smooth', // 平滑滚动过渡
        block: 'start' // 元素顶部对齐视口顶部
      });
    }
  }, [filteredMatches.upcoming]);

}

export default BasketballMatches;

4. 基础样式优化(可选)

添加简单样式区分赛事状态,提升用户体验:

.matches-wrapper {
  max-width: 900px;
  margin: 2rem auto;
  padding: 0 1rem;
}

.match-item {
  display: flex;
  justify-content: space-between;
  padding: 1rem;
  border-bottom: 1px solid #e5e7eb;
}

.finished-section .match-item {
  opacity: 0.7;
}

.status {
  color: #6b7280;
}

边界情况处理

  • 如果没有未开始赛事,自动滚动逻辑不会执行,页面停留在顶部
  • 若API返回数据为空,可添加空状态提示(比如<p>暂无赛事数据</p>)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 03:01:00