/ / undefined non è un oggetto (valutando '_this.props.date.getFullYear') - reactjs, react-native, react-native-ios

undefined non è un oggetto (valutando '_this.props.date.getFullYear') - reactjs, react-native, react-native-ios

Ho riscontrato un errore come questo:

inserisci la descrizione dell'immagine qui

e questi sono il mio codice

export default class StarView extends Component{
static propTypes = {
date : React.PropTypes.instanceOf(Date)
}
constructor(props){
super(props);
this.state = {
selectedYear: this.props.date.getFullYear(),
selectedMonth: this.props.date.getMonth(),
selectedDate: this.props.date.getDate(),
yesterdayYear : new Date(this.props.date.getTime() - 24 * 3600 * 1000).getFullYear(),
yesterdayMonth: new Date(this.props.date.getTime() - 24 * 3600 * 1000).getMonth(),
yesterdatDate : new Date(this.props.date.getTime() - 24 * 3600 * 1000).getDate(),
tomorrowYear : new Date(this.props.date.getTime() + 24 * 3600 *1000).getFullYear(),
tomorrowMonth : new Date(this.props.date.getTime() + 24 * 3600 *1000).getMonth(),
tomorrowDate : new Date(this.props.date.getTime() + 24 * 3600 *1000).getDate()
}
}}

Voglio ottenere un dato predefinito da this.props.date, ma non conosco il motivo per cui ho ricevuto l'errore

risposte:

4 per risposta № 1

Hai definito propTypes ma no defaultProps. Come ho capito, quello che vuoi è un valore predefinito per il prop date. In quel caso defaultProps è ciò che devi definire. Ecco un esempio:

export default class StarView extends Component{
static propTypes = {
date: React.PropTypes.instanceOf(Date)
}
static defaultProps = {
date: new Date()
}
constructor(props){
super(props);
this.state = {
selectedYear: this.props.date.getFullYear(),
selectedMonth: this.props.date.getMonth(),
selectedDate: this.props.date.getDate(),
yesterdayYear: new Date(this.props.date.getTime() - 24 * 3600 * 1000).getFullYear(),
yesterdayMonth: new Date(this.props.date.getTime() - 24 * 3600 * 1000).getMonth(),
yesterdatDate: new Date(this.props.date.getTime() - 24 * 3600 * 1000).getDate(),
tomorrowYear: new Date(this.props.date.getTime() + 24 * 3600 *1000).getFullYear(),
tomorrowMonth: new Date(this.props.date.getTime() + 24 * 3600 *1000).getMonth(),
tomorrowDate: new Date(this.props.date.getTime() + 24 * 3600 *1000).getDate()
}
}
}