我正在从 firebase 获取实时数据,并在收到更新后的数据时更新 useState 变量中的数据。
问题是,useState 组件内的数据会更新但不会呈现,除非我重新访问该选项卡。我已经尝试了我已知的所有可能的解决方案,但无法解决问题。
这是我的代码,
const blockItemsList: React.FC = () => {
const [showLoading, setShowLoading] = useState<boolean>(true);
const [blockData, setblockData] = useState([]);
const [isFirstTime, setFirstTime] = useState<boolean>(true);
var currentData = [];
const authTools = useAuth();
const dataRef = db
.collection("block")
.doc(authTools.getUserId())
.collection("details");
function filterAndUpdateData(newData, deletedData, modifiedData) {
var dataArr = currentData;
newData.map((doc) => {
dataArr.push(doc);
});
deletedData.map((doc) => {
dataArr = dataArr.filter((item) => item.id !== doc.id);
});
modifiedData.map((doc) => {
const index = dataArr.findIndex((element) => element.id === doc.id);
dataArr[index] = doc;
});
dataArr.map((doc) => {
console.log(doc.data());
});
setblockData(dataArr);
currentData = dataArr
if (isFirstTime) {
setFirstTime(false);
setShowLoading(false);
}
}
useEffect(() => {
const unsubscribe = dataRef.onSnapshot((querySnapshot) => {
var newData = [];
var deletedData = [];
var modifiedData = [];
const items = querySnapshot.docChanges().map((docObject) => {
if (docObject.type === "modified") {
modifiedData.push(docObject.doc);
} else if (docObject.type === "added") {
newData.push(docObject.doc);
} else if (docObject.type === "removed") {
deletedData.push(docObject.doc);
}
});
console.log("AAH SHSIT");
filterAndUpdateData(newData, deletedData, modifiedData);
if (isFirstTime) {
setFirstTime(false);
setShowLoading(false);
}
});
return () => unsubscribe();
}, []);
return (
<>
<IonPage>
{!!blockData &&
blockData.map((doc, index) => {
return (
<blockItem
key={doc.id}
num={index}
active={doc.data().health_status}
temperature={doc.data().temperature_faren}
/>
);
})}
</IonPage>
</>
);
};
非常感谢您的帮助。