0

我开始学习 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);

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

4

2 回答 2

2

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

let { firstName: fName, lastName: lName } = data?.profile;
let { all: totalGames, win: totalWins /* and so on */ } = data?.count;
于 2021-08-23T07:06:59.547 回答
0

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

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

于 2021-08-23T07:02:58.463 回答