() => {…} 与 () => 有何不同
+----+--------------------------------+---------------------------------------+
| # | Using curly brace | Without curly brace |
+-------------------------------------+---------------------------------------+
| 1. | Needs explicit return | Returns the statement implicitly |
| 2. | `undefined` if no return used | Returns the value of expression |
| 3. | return {} // ok | {} // buggy, ({}) // ok |
| 4. | Useful for multi-line code | Useful for single line code |
| 5. | Okay even for single line | Buggy for multi line |
+----+--------------------------------+---------------------------------------+
以下是上述差异的示例:
示例:1
// Needs explicit return
() => {
return value
}
// Returns the value
() => value
示例:2
// Returns undefined
() => {
1 == true
}
// Returns true
() => 1 == true // returns true
示例:3
// ok, returns {key: value}
() => {
return {key: value}
}
// Wrap with () to return an object
() => {key: value} // buggy
() => ({key: value}) // ok
示例:4
// Useful for multi-line code
() => {
const a = 1
const b = 2
return a * b
}
// Useful for single line code
() => 1 * 2
示例:5
// Okay even for single line code
() => { return 1 }
// Buggy for multi-line code
() => const a = 123; const b = 456; a + b; // buggy
() =>
const a = 123
const b = 456
a + b // still buggy
使用过滤功能时,return statement is required通过测试:
包含通过测试的元素的新数组。如果没有元素通过测试,则返回一个空数组。
因此,使用() => 形式,您隐式返回值,它将通过测试并正常工作。但是当您使用() => {...} 时,您并没有明确返回该语句,并且不会按预期工作。它只是返回一个空对象。
因此,要使您的代码按预期工作,您应该使用 return 语句:
this.state.articles.filter((article) => {
return article.category === filter
})
PS:我用的是隐式和显式两个词,在 JavaScript 中到底是什么?
隐式意味着 JavaScript 引擎为我们做这件事。明确意味着我们需要做我们想做的事。我们可以在任何方面进行类似的思考。