【问题标题】:Efficient way to use display the results from the fetch?使用显示提取结果的有效方法?
【发布时间】:2021-10-23 13:16:02
【问题描述】:

我开始学习 reactjs。我从给定的 API https://lichess.org/api/user/nihalsarin2004 获取结果,它显示了 Lichess 用户的个人资料。 (这里是 nihalsarin2004)。但是为了使用每个细节,我将它们编码如下:

let fName = JSON.stringify(data?.profile?.firstName);
let lName = JSON.stringify(data?.profile?.lastName);
let totalGames = JSON.stringify(data?.count?.all);
let totalWins = JSON.stringify(data?.count?.win);
let totalDraws = JSON.stringify(data?.count?.draw);
let totalLoss = JSON.stringify(data?.count?.loss);
let userLink = JSON.stringify(data?.url);
.
.
.
.
.
let blitzRating = JSON.stringify(data?.perfs?.blitz?.rating);
let bulletRating = JSON.stringify(data?.perfs?.bullet?.rating);
let rapidRating = JSON.stringify(data?.perfs?.rapid?.rating);
let classicalRating = JSON.stringify(data?.perfs?.classical?.rating);
let chess960Rating = JSON.stringify(data?.perfs?.chess960?.rating);
let antichessRating = JSON.stringify(data?.perfs?.antichess?.rating);
let checkRating = JSON.stringify(data?.perfs?.threeCheck?.rating);
let atomicRating = JSON.stringify(data?.perfs?.atomic?.rating);
let hordeRating = JSON.stringify(data?.perfs?.horde?.rating);

然后在反应组件中使用这些变量? 我们有什么替代方案吗?

【问题讨论】:

    标签: reactjs api fetch api-doc lichess


    【解决方案1】:

    您可以按如下方式对它们进行解构:

    if(!data.profile){
        // check if there is data and profile 
        // same for other keys in data obj
        return null
    }
    let {firstName, lastName} = data.profile
    let {all,win, draw, loss} = data.count
    // so on...
    

    注意:无论何时从对象中解构任何变量,请确保将该变量命名为与要提取的键相同的名称

    for example:
    let obj={
    name:"John",
    age:20,
    }
    
    // if you want to destructure obj you can do following
    let {name, age}=obj
    
    //variable names in {} should be same as key in obj
    
    

    【讨论】:

    • 就像 let {bullet,blitz,rapid,classical } = data.perfs,我们将子弹作为对象(例如:bullet : { games": 10755, "rating": 3050, "rd": 45,“前卫”:14,}
    • 是的,data.prefs 的任何数据类型项目符号键都只会呈现它,请确保添加对 data.prefs 的检查,因为如果它未定义,它将在解构时破坏代码
    【解决方案2】:

    使用Destructuring Assignment并在解构中分配一个新的变量名:

    let { firstName: fName, lastName: lName } = data?.profile;
    let { all: totalGames, win: totalWins /* and so on */ } = data?.count;
    

    【讨论】:

    • 警告:当 data.profile 未定义时,这将失败,请使用 data?.profile || {} 以便有一个对象可以从中解构。第二行也一样。
    猜你喜欢
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多