Redux - call action from a function

前端 未结 2 561
别跟我提以往
别跟我提以往 2021-01-21 11:32

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

2条回答
  •  难免孤独
    2021-01-21 12:02

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

    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)

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

    Putting it all together:

    import myFunc ...
    class MyComponent extends React.Component {
    
      onChange() {
        myFunc(this.props.actionCreator)
      }
    
      render() { ... }
    }
    
    export connect(null, { actionCreator })(MyComponent)
    

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

提交回复
热议问题