undefined is not an object (evaluating '_this.props.date.getFullYear')

Deadly 提交于 2021-01-29 03:18:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!