简体   繁体   中英

JavaScript anonymous function callback and redux-saga .next()

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:

  • Instead of using
onClick = {sum}

we use:

onClick ={() => sum}
  • Also, in the react course, I am wondering why do we call mapDispatchToProps like:
Increment: () => dispatch({type: 'INCREMENT'})

but not:

increment: dispatch({type: 'INCREMENT'})

Question 2:

  • When do we use sum() or sum in the click event, for example:
onClick = {sum()} OR onClick = {sum}

Question 3:

  • As we know that Redux-Saga implements generator function, but as from what I know, generator function when it has more than one yield, it requires next() in order to go on. However, in Redux-Saga, I don't see the use of next(), is that because the Sagas has already automatically called next() in it's function?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM