// bad
class Listing extends React.Component {
render() {
return <div>{this.props.hello}</div>;
}
}
// bad (relying on function name inference is discouraged)
const Listing = ({ hello }) => (
<div>{hello}</div>
);
// good
function Listing({ hello }) {
return <div>{hello}</div>;
}
这取自Airbnb react样式指南。有人可以解释为什么“不鼓励依赖函数名推断”吗?只是样式问题吗?
我认为这也可能与您可能会遇到的意外行为有关,从隐式地将词法名称赋予您可能希望使用的匿名函数可能会遇到这种意外行为。
例如说有人理解了箭头功能:
(x) => x+2;
要使常规功能等效:
function(x) {
return x+2;
}
期望这段代码非常容易:
let foo = (x) => x+2;
然后等于:
let foo = function(x) {
return x+2;
}
该函数仍然是匿名的,无法引用自身来执行诸如递归的操作。
因此,如果那时,在我们幸福的无知中,我们发生了这样的事情:
let foo = (x) => (x<2) ? foo(2) : "foo(1)? I should be a reference error";
console.log(foo(1));
它会成功运行,因为该函数显然不是匿名的:
let foo = function foo(x) {
return (x<2) ? foo(2) : "foo(1)? I should be a reference error";
}
在其他情况下,如果Babel隐式为匿名函数添加名称,这一事实可能会加剧这种情况(尽管我可能错了,但我认为实际上首先支持隐式函数名有些副作用。
),他们可以正确处理任何极端情况,并在您期望的地方抛出参考错误。
例如:
let foo = {
bar: function() {}
}
// Will surprisingly transpile to..
var foo = {
bar: function bar() {}
};
// But doing something like:
var foo = {
bar: function(x) {
return (x<2) ? bar(2) : 'Whats happening!?';
}
}
console.log(foo.bar(1));
// Will correctly cause a ReferenceError: bar is not defined
您可以在此快速演示中检查“查看已编译”,以了解Babel实际如何进行转译以维护匿名函数的行为。
简而言之,明确地说明正在执行的操作通常是一个好主意,因为您确切知道对代码的期望。不鼓励使用隐式函数命名,这可能是支持这一点的风格选择,同时也保持简洁明了。
可能正在吊装。但是,嘿,有趣的旅行。