Vyskytla sa chyba, ako je táto:
a toto je môj kód
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()
}
}}
Chcem získať predvolené údaje z this.props.date, ale ja neviem dôvod, prečo som chybu dostal
odpovede:
4 pre odpoveď č. 1Definovali ste propTypes ale nie defaultProps, Ako som pochopil, to, čo chcete, je predvolená hodnota pre prop date
, V tom prípade defaultProps je to, čo musíte definovať. Tu je príklad:
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()
}
}
}