【问题标题】:JavaScript anonymous function callback and redux-saga .next()JavaScript 匿名函数回调和 redux-saga .next()
【发布时间】:2020-12-21 07:37:03
【问题描述】:

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

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

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

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

  • 而不是使用
onClick = {sum}

我们使用:

onClick ={() => sum}
  • 另外,在 react 课程中,我想知道为什么我们将 mapDispatchToProps 称为:
Increment: () => dispatch({type: 'INCREMENT'})

但不是:

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

问题 2:

  • 我们什么时候在点击事件中使用sum()或者sum,例如:
onClick = {sum()} OR onClick = {sum}

问题 3:

  • 我们知道 Redux-Saga 实现了生成器函数,但据我所知,当生成器函数有多个产量时,它需要 next() 才能继续。 但是,在 Redux-Saga 中,我没有看到 next() 的使用,是因为 Sagas 已经在它的函数中自动调用了 next() 吗?

谢谢各位。非常感谢!

【问题讨论】:

标签: javascript reactjs redux-saga


【解决方案1】:

对于问题 1 和 2,onClick 属性需要一个以 event 作为第一个参数且不应返回任何内容的事件处理程序(这是一个函数定义)。

当点击按钮时,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 效果)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-26
    • 2022-01-15
    • 1970-01-01
    • 2018-01-22
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多