我正在从Firebase检索一些数据,该数据返回两个对象,我想将其存储为本地状态的数组。我试图使用扩展运算符来维持当前状态并附加新记录,但它似乎一直覆盖原始记录?
下面的代码从firebase返回两个对象,但我只能看到最后一个对象设置在状态。
const [date, setDate] = useState(new Date(new Date().setHours(0, 0, 0, 0))); //setting initial state to current day midnight
const [step, setStep] = useState(0); // Count the days ahead the user is trying to book.
const [alert, setAlert] = useState(false); // Alert when trying to exceed booking window.
const [bookings, setBookings] = useState([]);
const bookingWindowAllowed = 7; // Used to limit the forward bookings (evaluated vs state.step)
useEffect(() => {
setLoading(true);
setBookings([]);
//date as firestore timestamp
const setDate = firebase.firestore.Timestamp.fromMillis(
dayjs(date).valueOf()
);
//Compute tomorrow as firestore timestamp
const futureDate = firebase.firestore.Timestamp.fromMillis(
dayjs(date).add(1, 'day').valueOf()
);
// Get bookings from firestore
firestore
.collection('bookings')
.where('studio.ID', '==', 'kM8p1jSenI4M0Mr1PzBo')
.where('startTime', '>=', setDate)
.where('startTime', '<', futureDate)
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(doc.data());
setBookings([...bookings, doc.data()]);
});
setLoading(false);
})
.catch((error) => {
console.log('Error getting documents: ', error);
setLoading(false);
});
}, [date]);
ReactsetState
函数是异步的,这意味着它们不会立即改变状态,这就是为什么你正在实现的模式不像预期的那样工作。
最好将这两个对象保存在一个数组中,迭代结束后,将该数组保存为state:
useEffect(() => {
setLoading(true);
setBookings([]);
//date as firestore timestamp
const setDate = firebase.firestore.Timestamp.fromMillis(
dayjs(date).valueOf()
);
//Compute tomorrow as firestore timestamp
const futureDate = firebase.firestore.Timestamp.fromMillis(
dayjs(date).add(1, 'day').valueOf()
);
// Get bookings from firestore
firestore
.collection('bookings')
.where('studio.ID', '==', 'kM8p1jSenI4M0Mr1PzBo')
.where('startTime', '>=', setDate)
.where('startTime', '<', futureDate)
.get()
.then((querySnapshot) => {
const newBookings=[] /// create an empty array
querySnapshot.forEach((doc) => {
console.log(doc.data());
newBookings.push(doc.data()); // push each object to newBookings
});
setBookings(newBookings); // save it in state
setLoading(false);
})
.catch((error) => {
console.log('Error getting documents: ', error);
setLoading(false);
});
}, [date]);