React Redux this.props.getClasses不是一个函数

时间:2018-06-13 11:11:25

标签: reactjs redux react-redux redux-thunk

我正在尝试将mapDispatchToProps的操作传递给组件, 当我尝试使用getClasses作为this.props.getClasses()。 我收到失败道具类型:道具getClassesHierarchySelect中被标记为必需,但其值为undefined 并且'section'选择组件与 TypeError崩溃:this.props.getClasses不是函数

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';

const { Fragment } = React;
export class HierarchySelect extends Component {
  constructor (props) {
    super(props);
    this.state = {
      sections: [],
      section: '--',
    };
  }

  handleChange (value, type, error) {
    switch (type) {
      case 'section':
        this.setState({
          section: value
        });
        this.props.getClasses({ type: '', data: '' });
        break;
      default:
    }
  }

  render () {
    return (
      <Fragment>
        <select id="lang" className="section" onChange={e => this.handleChange(e.target.value, 'section')} value={this.state.section}>
          {['--', ...this.state.sections].map(d => <option key={d} value={d}>{d}</option>)}
        </select>
      </Fragment>
    );
  }
}

HierarchySelect.propTypes = {
  deptHierarchy: PropTypes.object.isRequired,
  createHierarchy: PropTypes.func.isRequired,
  id: PropTypes.number.isRequired,
  getClasses: PropTypes.func.isRequired
};

export const mapStateToProps = (state, props) => ({
  user: state.getUser
});

export const mapDispatchToProps = dispatch => ({

  getClasses: (data) => {
    dispatch(data);
  }

});

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

2 个答案:

答案 0 :(得分:1)

在mapDispatchToProps中,您没有在getClasses中返回调度。你需要把它写成

export const mapDispatchToProps = dispatch => ({
    getClasses: (data) => {
       return dispatch(data);
    }
});

export const mapDispatchToProps = dispatch => ({
  getClasses: (data) => dispatch(data);
});

此外,您还需要导入连接的组件,这是您案例中的默认导出

import HierarchySelect  from './hierarchy-dropdowns';

答案 1 :(得分:0)

handleChange未绑定到组件this instance.So,您将props定义为未定义。

使用

定义handleChange 执行lexical this绑定的

Arrow function

handleChange = (value, type, error) =>{
            this.props.getClasses();
        }
      }

OR

在构造函数中this绑定bind

constructor(){

   this.handleChange = this.handleChange.bind(this);
}