React必须返回有效的React元素(或null)。你可能已经返回undefined,

时间:2017-07-20 02:34:22

标签: reactjs react-redux

import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import * as courseActions from '../../actions/courseActions';

class CoursePage extends React.Component {

  constructor(props, context) {
  super(props, context);

this.state = {
  course: {title: ""}
};

/*
 To enhance performance declare all the bindings here,
 otherwise if they are declare in the mark up binding
 will have to take place during rendering which will take
 performance hit.
*/

this.onTitleChange = this.onTitleChange.bind(this);
this.onClickSave = this.onClickSave.bind(this);
}

onTitleChange(event) {
const course = this.state.course;
course.title = event.target.value;
this.setState({
  course: course
  });
}
 onClickSave() {
this.props.dispatch(courseActions.createCourse(this.state.course));
}

courseRow(course, index) {
  return <div key={index}>{course.title}</div>;
}

render() {
return (<div>
  <div>
    <h1>Courses</h1>
    {this.props.courses.map(this.courseRow)}
    <h2>Add Course</h2>
  </div>
  <input
    type="text"
    onChange={this.onTitleChange}
    value={this.state.course.title}
  />
  <input
    type="submit"
    value="Save"
    onClick={this.onClickSave}
  />
</div>);
}
}

CoursePage.prototype = {
dispatch: PropTypes.func.isRequired,
courses: PropTypes.array.isRequired
};

const mapStateToProps = (state, ownProps) => {
return {
  courses: state.courses
};
};

// since second parameter is not provided, connect ejects connect prop
export default connect(mapStateToProps)(CoursePage);

获得以下错误,我不确定为什么将CoursePage视为非反应组件

invariant.js:44 Uncaught Error: CoursePage(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
    at invariant (invariant.js:44)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:166)
    at ReactCompositeComponentWrapper.wrapper [as mountComponent] (ReactPerf.js:66)
    at Object.mountComponent (ReactReconciler.js:39)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:297)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:222)
    at ReactCompositeComponentWrapper.wrapper [as mountComponent] (ReactPerf.js:66)
    at Object.mountComponent (ReactReconciler.js:39)
    at ReactDOMComponent.mountChildren (ReactMultiChild.js:203)
    at ReactDOMComponent._createInitialChildren (ReactDOMComponent.js:628)

1 个答案:

答案 0 :(得分:1)

与您正在更改CoursePage原型的事实有关。如果您要使用PropTypes,则应使用CoursePage.propTypes = { ... }代替prototype。此外,反应版本&gt; = 15.5中不推荐使用propTypes。因此,您必须将其安装为单独的依赖项。