首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaScript匿名函数回调和redux .next()

问JavaScript匿名函数回调和redux .next()
EN

Stack Overflow用户
提问于 2020-09-02 07:05:13
回答 1查看 206关注 0票数 0

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

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

代码语言:javascript
复制
const sum = (a,b) => a + b

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

  • 而不是使用
代码语言:javascript
复制
onClick = {sum}

我们使用:

代码语言:javascript
复制
onClick ={() => sum}
  • 此外,在反应过程中,我想知道为什么我们这样称呼mapDispatchToProps:
代码语言:javascript
复制
Increment: () => dispatch({type: 'INCREMENT'})

但不是:

代码语言:javascript
复制
increment: dispatch({type: 'INCREMENT'})

问题2:

  • 例如,在单击事件中何时使用sum()或sum:
代码语言:javascript
复制
onClick = {sum()} OR onClick = {sum}

问题3:

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

谢谢你们。非常感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-02 08:51:34

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

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

在在反应中处理事件阅读更多内容

代码语言:javascript
复制
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效果)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63700356

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档