React中fetch获取接口数据后高效展示结果的替代方案有哪些?
高效提取Lichess接口字段的替代方案
这里给你两种常用的更简洁的实现方式,比逐个声明变量效率高很多,也方便后续维护:
方案1:嵌套解构 + 批量处理
先把父级字段解构出来,再批量处理子字段和JSON序列化逻辑:
// 先兜底data为空的情况,解构第一层父字段 const { profile = {}, count = {}, url: userLink = null, perfs = {} } = data ?? {}; // 解构二级基础信息字段 const { firstName: fName = null, lastName: lName = null } = profile; const { all: totalGames = null, win: totalWins = null, draw: totalDraws = null, loss: totalLoss = null } = count; // 解构所有棋类对应的字段 const { blitz, bullet, rapid, classical, chess960, antichess, threeCheck, atomic, horde } = perfs; // 统一批量序列化,不用逐个写JSON.stringify const [ fNameStr, lNameStr, totalGamesStr, totalWinsStr, totalDrawsStr, totalLossStr, userLinkStr, blitzRating, bulletRating, rapidRating, classicalRating, chess960Rating, antichessRating, checkRating, atomicRating, hordeRating ] = [ fName, lName, totalGames, totalWins, totalDraws, totalLoss, userLink, blitz?.rating, bullet?.rating, rapid?.rating, classical?.rating, chess960?.rating, antichess?.rating, threeCheck?.rating, atomic?.rating, horde?.rating ].map(val => JSON.stringify(val));
如果不需要把每个字段都声明为独立变量,还可以把结果整理成一个对象,使用的时候更方便:
const userInfo = { fName: JSON.stringify(profile.firstName), lName: JSON.stringify(profile.lastName), totalGames: JSON.stringify(count.all), // 其他基础字段... ratings: ratingKeys.reduce((res, key) => { res[key] = JSON.stringify(perfs[key]?.rating); return res; }, {}) } // 组件里直接使用 userInfo.fName、userInfo.ratings.blitz 即可
方案2:配置映射批量生成(适合字段多的场景)
如果后续需要新增提取的棋类评级,只需要改配置数组即可,不用新增大量重复代码:
// 配置所有需要提取的评级类型,新增字段直接往数组里加 const RATING_TYPES = ['blitz', 'bullet', 'rapid', 'classical', 'chess960', 'antichess', 'threeCheck', 'atomic', 'horde']; // 批量生成所有评级字段 const ratings = RATING_TYPES.reduce((result, type) => { result[`${type}Rating`] = JSON.stringify(data?.perfs?.[type]?.rating); return result; }, {}); // 使用时直接取对应字段即可,比如 ratings.blitzRating、ratings.bulletRating
优化建议
- 如果你需要的空值是
""而不是"null",可以把序列化的逻辑改成JSON.stringify(val ?? ''),自动把undefined、null值转为空字符串的序列化结果 - 可以把整个提取逻辑封装成独立的工具函数或者React自定义Hook,多个组件使用时直接调用即可,不用重复写提取逻辑
内容的提问来源于stack exchange,提问作者MagnusEffect
相关产品推荐
相关产品推荐

