我遇到了这样的错误:
这些是我的代码
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获取默认数据,但我不知道我收到错误的原因
答案 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()
}
}
}