undefined不是一个对象(评估' _this.props.date.getFullYear')

时间:2017-02-14 08:20:08

标签: reactjs react-native react-native-ios

我遇到了这样的错误:

enter image description here

这些是我的代码

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()
    }
}}

我想从this.props.date获取默认数据,但我不知道我收到错误的原因

1 个答案:

答案 0 :(得分:4)

您已定义propTypes但未定义defaultProps。据我所知,你想要的是道具date的默认值。在这种情况下,您需要定义 defaultProps 。这是一个例子:

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()
        }
    }
}