【问题标题】:Why the () in this.state when using the current state as a parameter为什么使用当前状态作为参数时this.state中的()
【发布时间】:2020-10-15 07:43:45
【问题描述】:
我正在阅读有关 Reactjs 的内容,以及以下语法中我不理解的一件事(取自 here)
this.setState(state => ({showWarning: !state.showWarning}))
是对象周围的 ()。我知道我们使用 () 表示 JSX,但对象 {showWarning: !state.showWarning} 是一个 JS 对象。我在使用 Redux 时也发现了这个符号
const mapStateToProps = state => ({...})
为什么我们在 React 中这样做?
【问题讨论】:
标签:
javascript
reactjs
redux
jsx
【解决方案1】:
没有具体的反应。箭头函数有一个简写,如果你只有一个语句,它允许你跳过显式返回。所以像这样的函数:
const example = (val) => {
return 'foo'
}
可以缩短为:
const example = (val) => 'foo';
但请注意,您这样做的方式是省略函数体的大括号。如果您尝试返回一个对象,您将在 in 大括号中粘贴,因此 javascript 认为“啊,这是函数体”,而实际上您希望括号表示对象字面量.为了消除歧义,您需要将对象包装在括号中,因此不可能将其解释为函数体。
const example2 = (val) => {
return { foo: 'bar' }
}
// can't become this:
//const example2 = (val) => {
// foo: 'bar' // this is not a key/value pair of an object! This is a labeled statement
//}
// so instead it becomes this:
const example2 = (val) => ({
foo: 'bar',
});
【解决方案2】:
这是运行返回对象的函数的 ES6 语法。
因为 Javascript 函数可以通过包裹花括号来创建新块,所以对于您是要创建这个新块还是尝试使用隐式返回返回一个对象存在一些歧义。因此,通过将对象包装在 () 中,您可以告诉 JS 您正在尝试将对象隐式返回。
它只是保持代码精简且更现代,这就是人们使用它的原因。
例子:
const ex1 = () => 1 // returns 1, no ambiguity
const ex2 = () => {return 1} // same as above, but with explicit return
const ex3 = () => {a: 1} // error! thinks it's a new block, not an object
const ex4 = () => ({a: 1}) // returns {a: 1} because wrapped in ()
【解决方案3】:
{showWarning: !state.showWarning} 绝对是一个有效的 javascript 对象,但不是在任何地方都可以作为对象工作,因为{} 也用于代码块。如果您从没有() 的箭头函数隐式返回任何对象,javascript 将认为它是代码块而不是对象
() 只是用来让引擎认为我们在这里尝试使用表达式而不是语句的代码块
【解决方案4】:
它不是 React 独有的。
使用Arrow functions 时,返回箭头右侧的表达式。但在对象的情况下,解释器会将大括号解释为多行函数。
括号表示要返回一个对象,而不是功能块声明。
引自Syntax section of MDN:
(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
// equivalent to: => { return expression; }
// Parentheses are optional when there's only one parameter name:
(singleParam) => { statements }
singleParam => { statements }
// The parameter list for a function with no parameters should be written with a pair of parentheses.
() => { statements }
// Parenthesize the body of a function to return an object literal expression:
params => ({foo: bar})