我开始学习reactjs了。我从给定的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);然后在react组件中使用这些变量?我们有没有别的选择呢?
发布于 2021-08-23 07:07:00
在解构中使用Destructuring Assignment并分配一个新的变量名:
let { firstName: fName, lastName: lName } = data?.profile;
let { all: totalGames, win: totalWins /* and so on */ } = data?.count;发布于 2021-08-23 07:02:58
您可以按如下方式分解它们:
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 objhttps://stackoverflow.com/questions/68888344
复制相似问题