0
我創建了一個組件並希望驗證其屬性之一。但它似乎驗證不起作用。當我訪問這個組件時,我總是得到屬性undefined錯誤:反應es6中的PropTypes不起作用
Cannot read property 'map' of undefined
以下是我的組件定義。
import React, {Component, PropTypes} from 'react'
import Carousel from 'nuka-carousel'
export default class DiagnosticSchedule extends Component {
render() {
let {style, diagnostics, afterSlide, beforeSlide} = this.props
// if(diagnostics === undefined){
// return (<div/>)
// }
return (
<div style={style}>
<Carousel style={style} decorators={null} afterSlide={afterSlide} beforeSlide={beforeSlide}>
{
diagnostics.map(diagnostic => {
return (
<div style={styles.message}>
{diagnostic.name}
</div>
)
})
}
</Carousel>
</div>
)
}
}
DiagnosticSchedule.propTypes = {
diagnostics: PropTypes.array.isRequired,
};
const styles = {
carousel:{
},
message: {
fontSize: 'xx-large',
flex: 1,
backgroundColor: 'red',
alignSelf: 'center',
lineHeight: '5',
zIndex: 100,
width: '100%',
textAlign: 'center',
}
}
我想下面的代碼是用來驗證這個組件的屬性。
DiagnosticSchedule.propTypes = {
diagnostics: PropTypes.array.isRequired,
};
,但它仍然抱怨說,診斷是一個未定義的對象。
我錯過了什麼嗎?或者我誤解了PropTypes驗證? PropTypes的預期行爲是什麼?
感謝
代替'getDefaultProps()'嘗試設置的'DiagnosticSchedule.defaultProps = {...}'。 –
是的,它的工作原理。我漫步DiagnosticSchedule.propTypes在這裏做什麼。如果我沒有DiagnosticSchedule.defaultProps,我的代碼會產生問題。 –
'getDefaultProps()'僅適用於'React.createClass'。 –