如何将多个 actionCreators 包装成一个 props?

IT技术 reactjs redux react-redux
2021-05-06 14:38:24

我收到以下错误:

Uncaught TypeError: this.props.dispatch is not a function

这是我的组件:

import React from 'react';
import PropTypes from 'prop-types';
import {Link} from 'react-router-dom';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as jobTitleSkillsActions from '../../actions/jobTitleSkillsActions';
import SkillList from './SkillList';
import * as userPositionActions from '../../actions/userPositionActions';

class SkillPage extends React.Component {

  componentDidMount() {
    this.props.dispatch(userPositionActions.loadUserPositions());
    var job_title_id = this.props.user_positions[0].job_title_id;    this.props.dispatch(jobTitleSkillsActions.loadJobTitleSkills(job_title_id));
  }

.....

const mapStateToProps = state => {
  return {
    job_title_skills: state.job_title_skills,
    user_positions: state.user_positions
  };
};

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

export default connect(mapStateToProps, mapDispatchToProps)(SkillPage);

我在这里做错了什么?

3个回答

根据我的评论,这将是绑定多个子对象value的动作创建者的正确语法:

function mapDispatchToProps(dispatch) {
    return {
        userPositionActions : bindActionCreators(userPositionActions, dispatch),
        jobTitleSkillsActions: bindActionCreators(jobTitleSkillsActions, dispatch),
    }
}

由于您已经使用mapDispatchToProps,dispatch不会作为props提供给组件。由于您已经使用过mapDisptachToProps,工作操作将作为props提供,您可以像这样使用它们

componentDidMount() {
    this.props.actions.userPositionActions.loadUserPositions());
    var job_title_id = this.props.user_positions[0].job_title_id;
    this.props.actions.jobTitleSkillsActions.loadJobTitleSkills(job_title_id));
  }

但是,您可以进一步简化它,例如

function mapDispatchToProps(dispatch) {
  return bindActionCreators({userPositionActions, jobTitleSkillsActions}, dispatch)  
}

...


componentDidMount() {
    this.props.userPositionActions.loadUserPositions());
    var job_title_id = this.props.user_positions[0].job_title_id;
    this.props.jobTitleSkillsActions.loadJobTitleSkills(job_title_id));
  }

正如您提供mapDispatchToProps的连接功能,分派不会作为props传递给您的组件。

您的 componentDidMount 代码应该是这样的:

componentDidMount() {
  const actions = this.props.actions
  actions.userPositionActions.loadUserPositions()
  var job_title_id = this.props.user_positions[0].job_title_id;
  actions.jobTitleSkillsActions.loadJobTitleSkills(job_title_id)
}