我在CodeReview问题中看到了这些模式:
toggleModal({title = null, description = null, cancelLabel = 'No', submitLabel = 'Yes'} = {}) {
this.setState({
modalVisible: !this.state.modalVisible,
title: title,
description: description,
cancelLabel: cancelLabel,
submitLabel: submitLabel
});
},
我想说这是ES6默认参数和破坏的组合。
试图了解目的。但还是不知道。
为什么不单独使用默认参数?
任何人都可以解释一下这种模式的含义吗?
答案 0 :(得分:3)
我会说它是ES6默认参数与解构的组合。
在JavaScript中我们称之为"参数,"不是参数,但是,是的,那是什么。它有三个部分。让我们逐个构建它:
解构。在函数中,我们希望将title
,description
等用作本地,因此我们声明了解构参数:
// Just the destructuring
toggleModal({title, description, cancelLabel, submitLabel}) {
我们希望这些单独的属性具有默认值,因此我们为它们分配默认值:
// Add in defaults for the props
toggleModal({title = null, description = null, cancelLabel = 'No', submitLabel = 'Yes'}) {
// ---------------^^^^^^^-------------^^^^^^^-------------^^^^^^^-------------^^^^^^^^
我们希望也使整个对象可选,因此我们为对象指定一个默认值:
// Add in a default for the object as a whole
toggleModal({title = null, description = null, cancelLabel = 'No', submitLabel = 'Yes'} = {}) {
// ------------------------------------------------------------------------------------^^^^^
所以这个:
toggleModal();
例如,没有争论,做同样的事情:
toggleModal({});
...因为总体默认值(上面的#3)开始了,这与此相同:
toggleModal({title: null, description: null, cancelLabel: 'No', submitLabel: 'Yes'});
...因为个人默认值(上面的#2)开始了。
因为参数是解构的,所以函数可以在体内使用title
,description
等(上面的#1)。
这是一个更简单的例子:
// REQUIRES ES2015+ SUPPORT IN YOUR BROWSER
function adams({answer = 42, question = "Life, the Universe, and Everything"} = {}) {
console.log("Answer: " + answer);
console.log("Question: " + question);
}
adams();
console.log("--");
adams({answer: 67});
console.log("--");
adams({question: "The mice are revolting!"});
console.log("--");
adams({
question: "Would you like a piece of cake?",
answer: "Yes, please!"
});

输出:
Answer: 42 Question: Life, the Universe, and Everything -- Answer: 67 Question: Life, the Universe, and Everything -- Answer: 42 Question: The mice are revolting! -- Answer: Yes, please! Question: Would you like a piece of cake?