我可以在 JavaScript 中的箭头函数中省略 Return 值吗?

Can I omit Return value in arrow function in JavaScript?

我为此苦恼了很久。我们都知道箭头函数简化了语法,像这样:

一个。箭头函数:

        onClick={() => toggleTodo(todo.id)}

乙。展开箭头函数:

        onClick={() => {
           // we can see there is a return keyword here. can I just remove the return keyword ? 
           return toggleTodo(todo.id); 
           ^^^^^^
        }}

redux官方教程中,文件AddTodo.js:

import React from 'react'
import { connect } from 'react-redux'
import { addTodo } from '../actions'

const AddTodo = ({ dispatch }) => {
  let input

  return (
    <div>
      <form
        onSubmit={e => {                   // focus on this line
          e.preventDefault()
          dispatch(addTodo(input.value)).  // focus on this line, if i put return here, the code below won't be executed. if not, how to explain the syntax in the beginning?
          input.value = ''
        }}
      >
        <input ref={node => (input = node)} />
        <button type="submit">Add Todo</button>
      </form>
    </div>
  )
}

export default connect()(AddTodo)

问题是:在onSubmit中,为什么我们不需要在函数体内放一个return?谢谢。

如果返回值将在某处使用,您只需要 return 一些东西。在 onSubmit 的情况下,不需要 return 任何东西。该(箭头)函数只是 运行 提交表单时的一些代码。

在你的问题中 B 点,是的,你可以删除 return if 不需要做任何事情toggleTodo(todo.id).

的返回结果

它们都是箭头函数

onClick={() => toggleTodo(todo.id)}

简短版

 onClick={() => {
    toggleTodo(todo.id);
 }}

长版

 onClick={() => {
    toggleTodo(todo.id);
    toggleTodo2(todo.id);
    toggleTodo3(todo.id);
 }}

长版本可以有多个调用,return不需要

当您使用同步函数并需要其结果时,您需要一个 return 值。

无论何时使用异步函数,都意味着调用函数本身已经继续,并且将通过回调函数进入下一阶段。

在您的例子中,window 对象是 onClick 的调用者,因此没有理由向它 return 赋值,它与它无关。

您确实想触发 React 的渲染机制,所以您使用调度 callback/trigger。