我正在尝试从函数中调用redux动作。我从中调用函数的组件已连接到商店。但是,如果我通过以下操作,则该操作将无效:
function myFunc(action) { action() }
有没有办法通过参数传递动作?谢谢。
该操作必须连接到一个调度程序上,以使reducer能够捕获它并更新商店。
为此,您应该将动作作为mapDispatchToPropsarg包含在redux的connect函数中。它看起来像这样:
mapDispatchToProps
connect(null, { actionCreator })(MyComponent)
要将连接的动作创建者从组件内部传递给功能,请通过props访问它: myFunc(this.props.actionCreator)
myFunc(this.props.actionCreator)
放在一起:
import myFunc ... class MyComponent extends React.Component { onChange() { myFunc(this.props.actionCreator) } render() { ... } } export connect(null, { actionCreator })(MyComponent)
现在,当myFunc执行时actionCreator(),它将正确分派要由减速器捕获的动作。
myFunc
actionCreator()