我將資料作為“陣列陣列”獲取,因此我必須將其更改為“物件陣列”,以便可以在我的產品頁面上使用它。
在主產品頁面中,我正確地對其進行了轉換,并且使用 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
uj5u.com熱心網友回復:
shift是突變。從來沒有在反應中改變過事物。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/489211.html
標籤:javascript 数组 反应 目的
下一篇:如何正確按下按鍵?
