在将元素添加到数组后,state覆盖这个数组,我将所有元素加倍,但添加的元素除外。 在从数据库获取此数组之前,我尝试了setArray([])
,但没有工作。
const [array, setArray] = useState([])
const [loading, setLoading] = useState(false)
useEffect(() => {
setLoading(true)
const objectRef = firebase.firestore().collection('obiekt').doc(object.id)
let startDay = new Date(props.date);
let endDay = new Date(props.date);
startDay.setHours(0, 0, 0, 0);
endDay.setHours(23, 59, 59, 999);
let datesArray = [];
firebase.firestore().collection("wydarzenie")
.where('obiekt', '==', objectRef)
.where('data_rozpoczecia', '>=', startDay)
.where('data_rozpoczecia', '<=', endDay)
.orderBy('data_rozpoczecia')
.onSnapshot(resp => {
resp.docs.map(el => {
datesArray.push({
...el.data(),
id: el.id
})
})
setLoading(false)
setArray(datesArray)
console.log(datesArray)
})
}, [])
[..]
{array && array.map(hour => {
return (
<div className={styles.CalendarInfoHour} key={hour.id}>
{moment(hour.data_rozpoczecia.toDate()).locale('pl').format('LT')}-
{moment(hour.data_zakonczenia.toDate()).locale('pl').format('LT')} Zajęte
</div>
)
})}
我不确定您到底想要什么,但是如果您正在覆盖以前的数组,并且希望避免这样做,请执行以下操作:
SetArray([...Array,newElementToAddToArray])
与其这样做:
let datesArray = [];
resp.docs.map(el => {
datesArray.push({
...el.data(),
id: el.id
})
})
请执行以下操作:
resp.docs.map(el => {
setArray({
...el.data(),
id: el.id
})
})