我有一個本地 json 檔案 ( data.json),我想將資料提取到我的 React 應用程式中。控制臺日志作業正常,但資料在 React 狀態下不可用。
我一直在關注這個博客。因此,我data.json在專案的public檔案夾下。
這是代碼:
應用程式.js
import React, { useState, useEffect } from "react";
import "./App.css";
function App() {
const [data, setData] = useState([]);
const getData = () => {
fetch("data.json", {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
})
.then(function (response) {
console.log("response", response);
return response.json();
})
.then(function (myJson) {
console.log("myjson", myJson);
setData(myJson);
});
};
useEffect(() => {
getData();
console.log("data is", data);
}, []);
return (
<div>
{data && data.length > 0 && data.map((item) => <p>{item.text}</p>)}
</div>
);
}
export default App;
Console.log 輸出以下內容:
data is []
data is []
response Response {type: 'basic', url: 'http://localhost:3000/data.json', redirected: false, status: 200, ok: true, …}
Response {type: 'basic', url: 'http://localhost:3000/data.json', redirected: false, status: 200, ok: true, …}
myjson {1: {…}, 2: {…}}
1: {text: 'first item', done: true}
2: {text: 'second item', done: false}
[[Prototype]]: Object
myjson {1: {…}, 2: {…}}
1: {text: 'first item', done: true}
2: {text: 'second item', done: false}
[[Prototype]]: Object
我已經閱讀了有關 stackoverflow 的幾個問題/答案,并且我了解資料是異步的,但我不知道如何僅在準備好時呼叫它。我嘗試過單獨的 useEffect 呼叫,但無濟于事。
uj5u.com熱心網友回復:
這只是回傳,在您的代碼中不起作用:
您會在此處的 console.log 中收到一個物件:
myjson {1: {…}, 2: {…}}
1: {text: 'first item', done: true}
2: {text: 'second item', done: false}
但是您嘗試data.在 return 中進行測驗,這將始終 yield undefined。
您可以測驗Object.values并使用它們進行映射以獲得所需的結果:
return (
<div>
{data && Object.values(data).length > 0 && Object.values(data).map((item) => <p>{item.text}</p>)}
</div>
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/514820.html
標籤:反应json
上一篇:反應:輸入欄位不更新文本
