我正在構建一個 Web 應用程式,它使用 Go 服務器向 React 應用程式提供資料。
在我的服務器的構建中,我遵循了 Go docs 提供的教程(https://golang.org/doc/tutorial/web-service-gin)。我的代碼與該代碼非常相似,當我使用curl時,我得到了預期的結果。
[
{
"id":0,
"date":"2021-11-21T12:00:00Z",
"rentedTo":"Bob",
"rentedBy":"Jim"
},
//etc...
然而,當我使用 React 的 fetch API 時,我的結果以意想不到的形式回傳。
fetch('http://localhost:8080/rentals')
.then((response)=> {
if (response.ok) {
return response.json();
}
throw response;
.then((jsonArr) => {
handleRentalsData(jsonArr)
})
.catch((error) => {
console.error("Error fetching data: ", error);
});
當 I 時console.log(jsonArr),瀏覽器報告以下內容:
Array(3) [ {...},{...},{...} ]
//Expanding this object via the console shows the following information:
---> 0: Object { id: 0, date: "2021-11-21T12:00:00Z", rentedTo: "Bob", ... }
---> 1: Object { id: 1, date: "2021-11-22T12:00:00Z", rentedTo: "Bob", ... }
---> 2: Object { id: 2, date: "2021-11-23T12:00:00Z", rentedTo: "Bob", ... }
這些索引(和瀏覽器的標簽)表明資料現在是陣列的形式,所以我這樣對待它。
我試圖遍歷這個陣列來決議其中的 json 字串,但JSON.parse(data)只生成數字(分別為 0、1 和 2)而不是生成物件,正如我預期的那樣。
for (const json in jsonArr){
console.log(typeof json); //string
const rentalObj = JSON.parse(json);
console.log(typeof rentalObj); //number
console.log(rentalObj); //0, 1, and 2 respectively
console.log(rentalObj.date); //undefined, because rentalObj is now a number.
}
我進行了一些搜索,并聽說資料傳入的陣列的索引可能會導致問題,因此我也嘗試使用 reviver 函式進行決議。
for (const json in jsonArr){
console.log(typeof json); //string
const rentalObj = JSON.parse(json, (key, value) => {
console.log(key); //<empty string>
console.log(value); //0, 1, and 2
return(value);
});
console.log(typeof rentalObj); //number
console.log(rentalObj); //0, 1, and 2 respectively
console.log(rentalObj.date); //undefined
}
JSON.parse(jsonArr)正如預期的那樣,嘗試拋出錯誤。我難住了。為什么它決議成一個(n 索引)數?在決議(或列印)陣列內的字串時,如何提取陣列內的物件只生成數字?
uj5u.com熱心網友回復:
中的json值for (const json in jsonArr) {將被設定為jsonArr陣列的“可列舉屬性” ,在這種情況下,它是索引。
for (const x in ['foo','bar','baz']) { console.log(x) };
// output:
// 0
// 1
// 2
所以你可能不想使用for ... in. 相反,您可以使用for ... of迭代陣列的元素:
for (const x of ['foo','bar','baz']) { console.log(x) };
// output:
// foo
// bar
// baz
陣列迭代和for ... in:
注意:
for...in不應用于迭代索引順序很重要的陣列。陣列索引只是具有整數名稱的可列舉屬性,在其他方面與一般物件屬性相同。不能保證
for...in會以任何特定順序回傳索引。該for...in回圈陳述句將回傳所有列舉的屬性,包括那些非整數的名字和那些繼承。因為迭代的順序是依賴于實作的,所以迭代陣列可能不會以一致的順序訪問元素。因此,在迭代訪問順序很重要的陣列時,最好使用
for帶有數字索引(或 回圈)Array.prototype.forEach()的for...of回圈。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364098.html
標籤:javascript 反应 json 走 获取-api
上一篇:Kafka登錄go服務
