获取的数据与旧数据不同,但看起来完全相同 [英] fetched data is different from old data, but seems exactly the same
问题描述
我有一个带有 Express 的 MongoDB,它在端点上提供数据,由 React 的 useEffect
访问:
I have a MongoDB with Express that serves the data on an endpoint, which is accessed by React's useEffect
:
function App() {
// const [responsive, setResponsive] = useState("vertical");
// const [tableBodyHeight, setTableBodyHeight] = useState("100%");
const [data, setData] = useState([]);
const [columns, setColumns] = useState([]);
// const options = {
// filter:true,
// filterType:'dropdown',
// responsive,
// }
// Fetch data / headers from express server
useEffect(() => {
const fetchData = async () => {
const resp = await fetch('http://localhost:4000/todos/');
const respData = await resp.json();
// Filter out irrelevant data
const keysToFilterOut = ['_id', '__v']
const firstDatum = respData[0];
const filteredDatum = _.omit(firstDatum, keysToFilterOut);
const filteredColumns = Object.keys(filteredDatum);
setData(respData);
setColumns(filteredColumns);
};
fetchData()
}, [data]);
useEffect
钩子一直被调用,这意味着 data
总是在变化.事实上,我通过在钩子中添加这 3 行来验证它:
The useEffect
hook is called all the time, which means the data
is somehow always changing. Indeed, I verified it by adding these 3 lines to the hook:
console.log(data === respData);
console.log(data);
console.log(respData);
并且第一个控制台日志确实是false
.我不明白,因为服务器没有更改数据,而且,我查看了另外 2 个控制台日志 - 它们看起来相同.数据有什么不同,怎么解决?
and the 1st console log is indeed false
. I don't get it, since the server didn't change the data, and moreover, I looked at the 2 other console logs - they seem identical. How is it that the data is different and how to fix it?
这是我的应用程序控制台日志中的一个示例:
Here is an example from the console log of my app:
推荐答案
因为在 JS 中:
像字符串和数字这样的原语通过它们的值进行比较,而像数组、日期和普通对象这样的对象通过它们的引用进行比较.
Primitives like strings and numbers are compared by their value, while objects like arrays, dates, and plain objects are compared by their reference.
并且由于这两个对象是两个不同的对象,因此它们没有相同的引用
and since those 2 objects are 2 different objects, they do not have the same referece
这篇关于获取的数据与旧数据不同,但看起来完全相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!