如何在不重新绑定 this 的情况下 return 具有粗箭头功能的对象?

How do you return an object with a fat arrow function without rebinding this?

我有一个简单的函数(在 React 组件中):

getInitialState: function() {
  return {
    text: this.props.text
  }
}

但我想给它加粗箭头:

getInitialState: () => {
    text: this.props.text
}

除了我得到一个错误,因为在粗箭头之后的 { 表示 return 未定义的代码块(除非你明确地 return 某些东西)。至少我一开始是这么想的。但我认为 this 现在被绑定到那个胖箭头函数,现在 this.propsundefined.

所以我试试这个:

getInitialState: () => new Object({
    text: this.props.text
})

但我得到同样的错误,this.props 未定义。

所以我想我有 2 个问题我很好奇。首先,从简单语句胖箭头函数 return 一个对象的惯用方法是什么?其次,如何 return 引用周围上下文的 this 对象的对象?

用括号括起来,像这样

getInitialState: () => ({
    text: this.props.text
})

没有括号,对象文字看起来也像一个 JavaScript 块,里面有一个名为 text 的标签。由于它不明确,因此抛出 SyntaxError。但是当你用 () 包围它时,JavaScript 知道它是一个对象文字。


I think this is being bound now to that arrow function

箭头函数没有 this。当在箭头函数中遇到 this 时,它将转到上一层以查看那里是否有 this 并使用它。你可以这样确认

(function Test1() {
  console.log(this);
  (() => console.log(this))();
}).bind({a: 1})();

会打印

{ a: 1 }
{ a: 1 }

在您的情况下,this 将引用声明它的函数的 this 对象,而不是对象本身。