问题
I encountered a error like this :
and these are my code
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()
}
}}
I want get a default data from this.props.date ,but I don't know the reason I get the error
回答1:
You have defined propTypes but not defaultProps. As I understand, what you want is a default value for the prop date
. In that case defaultProps is what you need to define. Here is an example:
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()
}
}
}
来源:https://stackoverflow.com/questions/42221015/undefined-is-not-an-object-evaluating-this-props-date-getfullyear