Ecmascript 6 如何从arrow函数隐式返回对象?

Ecmascript 6 如何从arrow函数隐式返回对象?,ecmascript-6,arrow-functions,Ecmascript 6,Arrow Functions,我使用以下箭头函数: 我想知道是否可以去掉{return…;}的额外层,基本上就是去掉块 如图所示,以下两个箭头功能相同: const fn = (a) => a + 1; const fn = (a) => { return a+1; }; 我可以从第二个更详细的版本中删除返回的 但是,当我对Redux示例执行相同操作并剥离返回层时,我得到一个错误: SyntaxError:repl,意外标记,应为 似乎在对象文本中的{}和代码块之间存在一些混淆。有没有办法删除这个额外的返回层?

我使用以下箭头函数:

我想知道是否可以去掉
{return…;}
的额外层,基本上就是去掉块

如图所示,以下两个箭头功能相同:

const fn = (a) => a + 1;
const fn = (a) => { return a+1; };
我可以从第二个更详细的版本中删除返回的

但是,当我对Redux示例执行相同操作并剥离返回层时,我得到一个错误:

SyntaxError:repl,意外标记,应为


似乎在对象文本中的
{}
和代码块之间存在一些混淆。有没有办法删除这个额外的返回层?

您可以通过添加这样的额外括号来防止混淆-

export const addTodo = (text) => (
  {
    type: 'ADD_TODO',
    id: nextTodoId++,
    text
  })

希望对您有所帮助:)

您还可以使用更明确的
对象。分配
(可以说)具有更好的可读性:

const addTodo = text => Object.assign({
  type: 'ADD_TODO',
  id: nextTodoId++,
  text
})
const addTodo = text => Object.assign({
  type: 'ADD_TODO',
  id: nextTodoId++,
  text
})