我将数据作为“数组数组”获取,因此我必须将其更改为“对象数组”,以便可以在我的产品页面上使用它。
在主产品页面中,我正确地对其进行了转换,并且使用 console.log,我可以正确地看到“对象数组”。在我将这个“对象数组”传递到我的产品页面以便我可以使用“对象数组”中的数据之后,各个对象被重新排列并弄乱了。我一直试图了解出了什么问题,但我无法调试它。请帮忙。
我的产品页面:
import React, { useState } from "react";
import Product from "./Product";
function Products() {
//State management for the data pulled using fetch
// data comes in as an array of arrays
// so I have to transform into an array of objects
const [data, setData] = useState([]);
// using the first array in the 'array of arrays' as keys
const keys = data.shift();
// transforming from 'array of arrays' to 'array of objects'
const dataObj = data.map(elem => ({
[keys[0]]: elem[0],
[keys[1]]: elem[1],
[keys[2]]: elem[2],
[keys[3]]: elem[3],
}));
console.log(dataObj)
// pulling data from excel sheet
const getData = () => {
fetch(
"https://sheets.googleapis.com/v4/spreadsheets/1DpaMUmqYxGUKnT9BL0uBuCZ6WJ8vd1CLAklqUvkcA8M/values/Sheet1?alt=json&key=AIzaSyD6o4v215zWtw-kOqGVeuLG50pE2QeRZTg",
{
method: "GET",
}
)
.then((response) => response.json())
.then((data) => {
// console.log(data.value);
setData(data.values);
});
};
return (
<div>
Hello, you're in the products page
<button onClick={getData}>click me</button>
{dataObj.map((prod) => (
<Product prod={prod} key={prod.id}/>
))}
</div>
);
}
export default Products;
我的产品页面
import React from "react";
function Product(props) {
console.log(props.prod);
return (
<div>
</div>
);
}
export default Product;
请忽略空数组。第一个数组是我的“对象数组”,它排列得当,但其他部分是单个对象,它们被弄乱了。
编辑:data.value
shift
是突变。从来没有在反应中改变过事物。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句