2017-07-20 79 views
0
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將被視爲非反應成分React必須返回有效的React元素(或null)。你可能已經返回undefined,

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

您的組件看起來很適合我。也許可能是因爲你正在改變CoursePage的原型?如果你想使用PropTypes,你應該使用'CoursePage.propTypes = {...}'而不是原型。另外,propTypes在反應版本> = 15.5中被棄用。所以你必須把它作爲一個單獨的依賴來安裝。 –

+0

這就是問題所在,非常好,我想把這個問題推廣到一個答案。 – eugenekgn

+1

我在下面添加了我的答案。 –

回答

1

這是與事實,你改變的原型做CoursePage。如果你想使用PropTypes,你應該使用CoursePage.propTypes = { ... }而不是prototype。另外,propTypes在反應版本> = 15.5中已棄用。所以你必須把它作爲一個單獨的依賴來安裝。

相關問題