简体   繁体   English

动态解构 props React

[英]Destructuring props dynamically React

Imaging we have a props , a really large object:想象我们有一个props一个非常大的object:

{
 "firstname": "John", 
 "lastname": "Doe",
 "age": 11,
 "mode: "expert",
 "website": "stackoverflow.com"
 "protocol": "https",
 "job": "dev",
 "env": "main",
 ..... and a lot of key-values pairs coming
} 

What usually we are calling to create "component variables":通常我们调用什么来创建“组件变量”:

let {firstname, 
     lastname, 
     age, 
     mode,
     website,
     protocol,
     job,
     env
     ...and a lot of "keys" as variable names} = props
// so we can call variable, {age} for example

I don't like to type all these variables in let {} , do we have something dynamic to declare "all keys" dynamically?我不喜欢在let {}中键入所有这些变量,我们有动态的东西来动态声明“所有键”吗? I am not sure it's possible.我不确定这是否可能。

Of course I can use {props.firstname} in my code.当然,我可以在我的代码中使用{props.firstname}

There is a way to create dynamically variables in let {} scope? let {} scope 中有动态创建变量的方法吗?

Any help is appreciated.任何帮助表示赞赏。

You can get all keys dynamically by Object.keys您可以通过Object.keys动态获取所有密钥

 const obj = { "firstname": "John", "lastname": "Doe", "age": 11, "mode": "expert", } const keys = Object.keys(obj) console.log(keys) //from these keys, you can get values based on your needs //the first key value is `firstname` //the first value is `John` console.log(keys[0], obj[keys[0]])

Do you want to use (destructure) some props, and leave the rest in another object?你想使用(解构)一些道具,把 rest 留在另一个 object 中吗? You can do that with ie你可以用 ie 做到这一点

let testobject = {
 "firstname": "John", 
 "lastname": "Doe",
 "age": 11,
 "mode": "expert"
}

const {firstname, lastname, ...verySmartFunc} = testobject ;

console.log(verySmartFunc);
//now your object is verySmartFunc, 
//created with those keys you haven't destructured, and has next properties
{
  age: 11,
  mode: "expert"
}

If that's not what you're looking for and I misunderstood your question, I'd say you're already having props as an object with all those keys.如果那不是您要找的东西并且我误解了您的问题,我会说您已经拥有带有所有这些键的 object 道具。

EDIT: Maybe this is what you're looking for, based on Nick Vu's answer.编辑:根据 Nick Vu 的回答,也许这就是您要找的东西。

const obj = {
 "firstname": "John", 
 "lastname": "Doe",
 "age": 11,
 "mode": "expert",
} 

const keys = Object.keys(obj)
let i = 0;
for (var key in keys) {
    window[keys[i]] = obj[keys[i]];
  i++
}


console.log(firstname); //result is "John"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM