Reputation: 365
I've been struggled from this for a long time. we all know that arrow function simplifies the syntax, like this:
A. Arrow function:
onClick={() => toggleTodo(todo.id)}
B. Expand the Arrow function:
onClick={() => {
// we can see there is a return keyword here. can I just remove the return keyword ?
return toggleTodo(todo.id);
^^^^^^
}}
In the official redux tutorial, the file 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)
The question is: in the onSubmit
, why we don't need to put a return
inside the function body ? Thank you.
Upvotes: 3
Views: 2700
Reputation: 6066
You need a return value when you use a synchronized function and need its result.
Whenever you use an asynchronous function, it means that the calling function already continued with itself and moving to the next phase will be via a callback function.
In your case the window
object is the caller of the onClick
, so there's no reason to return a value to it, it will have nothing to do with it.
You do want to trigger react's rendering mechanism so you use the dispatch callback/trigger.
Upvotes: 1
Reputation: 11940
onClick={() => toggleTodo(todo.id)}
Short version
onClick={() => { toggleTodo(todo.id); }}
Long version
onClick={() => { toggleTodo(todo.id); toggleTodo2(todo.id); toggleTodo3(todo.id); }}
Long version can have multiple calls, return
not required
Upvotes: 1
Reputation: 5118
You only need to return
something if that returned value will be used somewhere. In the case of onSubmit
, there is no need to return
anything. That (arrow) function is simply running some code when the form is submitted.
In point B in your question, yes, you can remove return
if nothing needs to be done with the returned result of toggleTodo(todo.id)
.
Upvotes: 6