当数组更改时,React 不会重新渲染我的组件?



我为各种清单设置了不同的排序选项,并为我的清单设置了一个空数组。使用firebase作为后端,所以基本上一切都在工作,但是在useEffect完成它的工作后数据不显示。只要我改变排序选项,列表就会出现。刷新后又一样了。我将列表和排序作为道具传递给另一个子组件,这是一个网格布局。每次我必须手动更改排序以便查看数据,如何才能使它根据排序选项自动显示数据。

const [sort, setSort] = useState("option1");
const [listings, updateListings] = useState([]);
const db = getFirestore();
const colRef = collection(db, "Listing");
useEffect(() => {
let defaultListings = [];
getDocs(colRef)
.then((snapshot) => {
snapshot.docs.forEach((doc) => {
defaultListings.push({ ...doc.data(), id: doc.id });
});
})
.catch((err) => {
console.log(err.message);
});
updateListings(defaultListings);
}, []);
return(<Listing list = {listings} sortoption={sort} />)

这个清单组件显示了网格

我试过添加依赖项,但它会导致无限循环,而没有任何依赖项的组件不显示任何东西。

您需要在then中调用updateListings,否则在修改defaultListings数组之前它会运行。

:

getDocs(colRef)
.then((snapshot) => {
snapshot.docs.forEach((doc) => {
defaultListings.push({ ...doc.data(), id: doc.id });
});
updateListings(defaultListings); // 👈
})
.catch((err) => {
console.log(err.message);
});

最新更新