JavaScript 匿名函数回调和 redux-saga .next()

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

我现在已经经历了几个 JavaScript 概念,包括几个反应传达,有几个问题我想知道并希望得到你们的帮助。

假设我们有一个函数名 sum:

const sum = (a,b) => a + b

问题一: 我已经看到很多匿名函数被调用来调用另一个函数,我想知道为什么我们这样做而不是直接调用那个特定的函数。例如:

onClick = {sum}

我们使用:

onClick ={() => sum}
Increment: () => dispatch({type: 'INCREMENT'})

但不是:

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

问题 2:

onClick = {sum()} OR onClick = {sum}

问题 3:

谢谢大家。非常感谢!

对于问题 1 和 2,onClick 属性 需要一个以 event 作为第一个参数且不应该 return 任何东西。

单击按钮时,onClick 函数调用,将 event 作为第一个参数传递。

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'})

对于问题 3,redux-saga 充当生成器运行程序,已为您处理调用 next() 的过程。您只需要定义生成器函数(结合使用它们的 redux-saga 效果)