使用ComponentDidMount中的props调用Action

时间:2017-01-31 13:29:18

标签: javascript reactjs redux react-redux

我从具有在reducer上定义的属性的componentDidMount调用一个动作,但当它到达动作时,参数未定义。

在我的组件中,我调用了动作" fetchAppClasses"使用属性(this.props.selection):

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

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

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

这是reducer返回的状态:

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 个答案:

答案 0 :(得分:0)

尝试在return功能中调用axios之前删除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));
      });
  };
}