[英]destructuring default values in function params
I'm trying to destructure values directly in params fonction and affect default values with a general object (for each subProperties destructured) :我正在尝试直接在 params 函数中解构值并使用一般对象影响默认值(对于每个被解构的子属性):
Example例子
const initialTest = {
name: 'myName',
surname: 'mySurname',
age: 100,
};
const MyComponent = ({
test: { name, surname, age } = initialTest,
}) => { ... }
<MyComponent test={{ name: 'myNameFromProps' }} />
My final desir is to have 3 const name
, surname
and age
, with values from props
(params of the function) if they are defined, and values from initialTest
if not.我的最终愿望是拥有 3 个 const
name
, surname
和age
,如果定义了props
(函数的参数),则使用来自initialTest
值。
With this code, if test
is not defined in props of component, it will use initialTest, but if test is defined with only name
props like example above, I will get :使用此代码,如果
test
未在组件的 props 中定义,它将使用 initialTest,但如果 test 仅使用name
props 定义,如上面的示例,我将得到:
name = 'myNameFromProps'
surname undefined
age undefined
and I want :而且我要 :
name = 'myNameFromProps'
surname = 'mySurname'
age = 100
For sur I can do it with :对于 sur 我可以这样做:
const MyComponent = ({
test: { name = initialTest.name, surname = initialTest.surname, age = initialTest.age },
}) => { ... }
But that's absolutly not funny...但这绝对不好笑......
I tried with parentheses test: ({ name, surname, age } = initialTest),
but does not works and eslint is saying I'm a stupid dev... and he is right xD我尝试使用括号
test: ({ name, surname, age } = initialTest),
但不起作用,eslint 说我是一个愚蠢的开发者......他是对的 xD
If you have any suggestions / idea / solution, I would be happy to read it.如果您有任何建议/想法/解决方案,我很乐意阅读。 Thx to all !
谢谢大家!
Unless you're actually using initialTest
elsewhere, you can remove it and list the default values inside the destructuring of test
:除非你真的在别处使用
initialTest
,否则你可以删除它并在test
的解构中列出默认值:
const MyComponent = ({
test: { name: 'myName', surname: 'mySurname', age: 100 } = {},
}) => { ... }
Make sure to have the = {}
at the end there, in case nothing exists in the test
property.确保在末尾有
= {}
,以防test
属性中不存在任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.