I've been going through several JavaScript concepts now, including a several react conveys, and there's a couple of questions that I am wondering and wishing to get help from you guys.
Suppose we have a function name sum:
const sum = (a,b) => a + b
Question 1: I've seen a lot of anonymous functions being called to call another function, I am wondering the reason why we do that instead of calling that specific function directly. For example:
onClick = {sum}
we use:
onClick ={() => sum}
Increment: () => dispatch({type: 'INCREMENT'})
but not:
increment: dispatch({type: 'INCREMENT'})
Question 2:
onClick = {sum()} OR onClick = {sum}
Question 3:
Thanks guys. Much appreciated!
For the question 1 and 2, the onClick
property expects a event handler (which is a function definition) that has the event
as the first parameter and should not return anything.
When the button is clicked, the onClick
function invokes, passing the event
as the first argument.
Read more at Handling Events in React
const sum = (a, b) => a + b
// an `event` will be passed as the first argument, the second argument gets undefined
onClick={sum}
// you could opt out the `event` parameter and call `sum` with your arguments
onClick={() => { sum(5, 10) }}
onClick={() => sum(5, 10)} // this will return the value of `sum(5, 10)` to the caller of onClick, which is not useful since the caller don't expect that
=> Using anonymous callback gives you the ability to call the function with specific arguments
// invalid usages, calling the function immediately which will assign the returned value to `onClick`, and the that returned value is not a function definition
onClick={sum(5, 10)}
increment: dispatch({type: 'INCREMENT'})
For the question 3, redux-saga
acts as a generator runner that has handled calling next() for you. You only need to define the generator function (in combination with using their redux-saga
effects)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.