Redux - 从函数调用操作 [英] Redux - call action from a function

查看:28
本文介绍了Redux - 从函数调用操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从函数调用 redux 操作.我从中调用函数的组件已经连接到商店.但是,如果我通过以下操作则不起作用:

I'm trying to call a redux action from a function. The component that I'm calling the function from is already connected to the store. However, it doesn't work if I pass the action such as:

function myFunc(action) {
    action()
}

有没有办法通过参数传递动作?谢谢.

Is there a way to pass an action via a parameter? Thank you.

推荐答案

action 必须连接到一个 dispatch,reducer 才能捕获它并更新 store.

The action must be connected to a dispatch for the reducer to catch it and update the store.

为了做到这一点,您应该将您的操作作为 mapDispatchToProps 参数包含在 redux 的连接函数中.它看起来像这样:

In order to do this you should include your action as a mapDispatchToProps arg for redux's connect function. It would look like this:

connect(null, { actionCreator })(MyComponent)

要将连接的动作创建者传递给组件内的函数,请通过 props 访问它:myFunc(this.props.actionCreator)

To pass the connected action creator to a function from within the component, access it via props: myFunc(this.props.actionCreator)

综合起来:

import myFunc ...
class MyComponent extends React.Component {

  onChange() {
    myFunc(this.props.actionCreator)
  }

  render() { ... }
}

export connect(null, { actionCreator })(MyComponent)

现在当 myFunc 执行 actionCreator() 时,它会正确地分派 action 以被你的 reducer 捕获.

Now when myFunc executes actionCreator() it will properly dispatch the action to be caught by your reducer.

这篇关于Redux - 从函数调用操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆