使用 ComponentDidMount 中的props调用 Action

IT技术 javascript reactjs redux react-redux
2021-05-01 05:46:56

我正在从具有在减速器上定义的属性的 componentDidMount 调用操作,但是当它到达操作时,参数未定义。

在我的组件中,我使用属性 (this.props.selection) 调用操作“fetchAppClasses”:

 componentDidMount() {
    this.props.actions.fetchAppClasses(this.props.selection);    
  }    

function mapStateToProps(state, ownProps) {
  return {
    selection: state.SDWanSelectionReducer
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(sDWanActions, dispatch)
  };
}

这是减速器返回的状态:

const selection = {
  timespan: "-3660",
  customTimespan: false,
  pathIds: [''],
  source: undefined,
  direction: 0,
  appClassIds: []
};

这里在变量“selection”中应该可以使用传递的参数但未定义:

       export function fetchAppClasses(selection) {
          return function (dispatch) {
            var axcfg = { headers: { 'X-Auth-Token': window[config.storageType].token } };
            return axios.get(config.apiUrl + '/sdwan/appClasses', axcfg)
              .then(function (response) {
                console.log('SDWanActions.fetchAppClasses response:', response);
                dispatch(fetchAppClassesSuccess(response.data));
              })      
          }
        }
1个回答

尝试删除函数中returnaxios 调用之前的fetchAppClasses

export function fetchAppClasses(selection) {
  return function(dispatch) {
    var axcfg = {
      headers: { 'X-Auth-Token': window[config.storageType].token },
    };

    // remove the return axios.get...
    axios.get(config.apiUrl + '/sdwan/appClasses', axcfg)
      .then(function(response) {
        console.log(selection); // this should work now...
        console.log('SDWanActions.fetchAppClasses response:', response);
        dispatch(fetchAppClassesSuccess(response.data));
      });
  };
}