【发布时间】:2020-10-29 17:11:11
【问题描述】:
React 新手。我试图保持一个跟踪一系列日历事件的状态。我将状态设置为等于一些 dummyData,如果将新的日历事件传递给 UserEvents(props),那么我想将其添加到 calendarList 状态。
它给出了一个错误,即 calendarList.push() 不是一个函数。当我 console.log 时,它是一个数组,所以我不明白为什么我不能对其使用 push() 方法。
import React, { useEffect, useState } from 'react';
import Countdown from '../countdown/Countdown';
function UserEvents(props){
let dummyData = [
{name: "birthday", date: '03/20/2021'},
{name: "christmas", date: '12/25/2020'},
{name: "thanksgiving", date: '11/26/2020'}
]
const [calendarList, setCalendarList] = useState(dummyData);
if(props.calendarItem){
setCalendarList(calendarList.push( props.calendarItem ));
}
return (
<div className="App">
{
calendarList.map((item, index) => {
return(
<Countdown name={item.name} date={item.date}></Countdown>
)
})
}
</div>
)
}
export default UserEvents;
如果你 console.log(calendarList) 显示它是一个对象,但也会打印“4”。如您所见,它会执行两次,我也不确定为什么。
【问题讨论】: