如何从箭头函数隐式 return 对象?

How to implicitly return object from arrow function?

我在 Redux example:

中使用了这个箭头函数
export const addTodo = (text) => {
  return {
    type: 'ADD_TODO',
    id: nextTodoId++,
    text
  }
}

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

为了说明,以下两个箭头函数是相同的:

const fn = (a) => a + 1;
const fn = (a) => { return a+1; };

我可以从第二个更详细的版本中删除 return

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

SyntaxError: repl, unexpected token, expected ; ...

对象字面量和代码块中的{}似乎有些混淆。有没有办法在这里删除这个额外的 return 层?

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

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

希望对您有所帮助:)

您还可以使用更明确的 Object.assign 以获得(可以说)更好的可读性:

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