Redux - call action from a function

2019-07-22 12:44发布

问题:

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.

回答1:

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.



回答2:

using bindActionCreator from redux is the easiest way to dispatch actions from the component.

import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

class ReduxConnectedComponent extends React.Component {
 mainFunction = () =>{
  this.props.someAction(); // this dispatches your action.
  }
 render(){}
}
const mapStateToProps = store => ({
  test: store.modules.someObject,
});

const mapDispatchToProps = dispatch => bindActionCreators({
  someAction: yourActionCreatorFunction,
}, dispatch);
export default connect(maStateToProps,mapDispatchToProps)(ReduxConnectedComponent)

here in mapDispatchToProps, we are using bindActionCreator to bind a function to redux store dispatch. so that whenever you call it. it actually dispatches the store action