对象作为 React 子对象无效.(找到:日期(印度标准时间))如果要呈现子项集合,请改用数组



你好,我正在使用反应日历。

https://www.npmjs.com/package/react-calendar

我的代码看起来像:

class ListingProcess extends Component {
constructor(props) {
super();
this.state = {
location: {
startDate: '',
endDate: '',
},
this.handleStartDate = this.handleStartDate.bind(this);
};
handleStartDate(date){
alert(date)
var locationObj = this.state.location;
locationObj.startDate = date;
this.setState({location: locationObj})
}

render() {
return (
<div>
<Calendar
onChange={this.handleStartDate}
value={this.state.location.startDate}
/>
</div>
);
}
}

每当我在控制台上设置状态中的开始日期值时显示错误

错误是:对象作为 React 子项无效(找到:2019 年 9 月 20 日星期五 00:00:00 GMT+0530(印度标准时间((。如果要呈现子项集合,请改用数组。

请帮忙。

您可能正在尝试直接呈现日期。不知何故,您需要从日期对象中获取所需的信息。我在这里使用 toDateString(( 作为示例。

此外,不要像在handleStartDate方法中的代码中那样直接改变状态。你应该像我一样更新你的状态,而不是直接改变它。

class ListingProcess extends React.Component {
constructor(props) {
super();
this.state = {
location: {
startDate: "",
endDate: ""
}
};
this.handleStartDate = this.handleStartDate.bind(this);
}
handleStartDate(startDate) {
this.setState(state => ({
location: {
...state.location,
startDate,
}
}));
}
printDate() {
return <p>{this.state.location.startDate.toDateString()}</p>;
}
render() {
return (
<div>
<Calendar
onChange={this.handleStartDate}
value={this.state.location.startDate}
/>
{this.state.location.startDate && this.printDate()}
</div>
);
}
}

最新更新