Redux - call action from a function

前端 未结 2 593
别跟我提以往
别跟我提以往 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 11:55

    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

提交回复
热议问题