Svelte中可打印teams数组却无法在{#each}块取值的问题
Svelte中遍历赛事数据时获取对应球队信息的解决方法
你的问题核心是:teams是所有赛事(fixture)的参赛球队扁平后的数组,和当前遍历的单个fixture没有关联,直接访问teams.short_code自然会返回undefined——数组本身没有short_code属性,只有数组里的每个球队对象才有。
下面提供两种可行的解决方式:
方式一:直接使用当前fixture自带的participants数据
每个fixture本身就包含participants数组(主客队信息),不需要单独提取全局的teams数组,直接在遍历fixture时访问其内部的participants即可:
修改+page.svelte代码:
<script> export let data; const { fixtures } = data; </script> <div class="flex flex-col absolute top-[0] right-0 w-[85vw] p-6"> <div> {#each fixtures as fixture} <p>{fixture.name}</p> <div>{fixture.home_score} - {fixture.away_score}</div> <!-- 遍历当前赛事的所有参赛球队 --> {#each fixture.participants as team} <p>{team.short_code}</p> {/each} <!-- 或者精准提取主/客队 --> <p>主队: {fixture.participants.find(t => t.meta.location === 'home')?.short_code}</p> <p>客队: {fixture.participants.find(t => t.meta.location === 'away')?.short_code}</p> {/each} </div> </div>
方式二:提前关联赛事与球队数据(更优)
如果希望数据结构更清晰,可以在服务端(+page.server.js)提前处理数据,给每个fixture添加homeTeam和awayTeam属性,组件里直接访问即可:
修改+page.server.js:
export const load = async () => { const fetchList = async () => { const url = `https://api.sportmonks.com/v3/football/schedules/seasons/19734?api_token=${process.env.API_KEY}`; const res = await fetch(url); const data = await res.json(); // 扁平化赛事数据并关联主客队 return data.data .flatMap(stage => stage.rounds.map(round => round.fixtures)) .flat() .map(fixture => { const homeTeam = fixture.participants.find(t => t.meta.location === 'home'); const awayTeam = fixture.participants.find(t => t.meta.location === 'away'); return { ...fixture, homeTeam, awayTeam }; }); }; return { fixtures: fetchList(), }; };
然后在+page.svelte里直接使用:
<script> export let data; const { fixtures } = data; </script> <div class="flex flex-col absolute top-[0] right-0 w-[85vw] p-6"> <div> {#each fixtures as fixture} <p>{fixture.name}</p> <div>{fixture.home_score} - {fixture.away_score}</div> <p>主队: {fixture.homeTeam.short_code}</p> <p>客队: {fixture.awayTeam.short_code}</p> {/each} </div> </div>
内容的提问来源于stack exchange,提问作者joshisitalian
相关产品推荐
相关产品推荐

