[英]Unable to access nested object from JSON data
我在 React 中有以下功能組件:
function GetData() {
const [randomDataJSON, setRandomDataJSON] = useState('');
const url = 'https://randomuser.me/api/';
const getData = () => {
axios
.get(`${url}`)
.then((results) => {
const userData = results.data.results;
setRandomDataJSON(JSON.stringify(userData, null, 2));
})
.catch((err) => console.error(err));
};
return (
<div>
<h3>GetData Component</h3>
<pre>{randomDataJSON[0].name.first}</pre>
<button onClick={getData}>Get Data</button>
</div>
);
}
export default GetData;
來自 API 的 JSON 數據如下:
[
{
"gender": "female",
"name": {
"title": "Miss",
"first": "Barbara",
"last": "Sullivan"
},
...
我想通過在<pre>
標簽中使用{randomDataJSON[0].name.first
來訪問和顯示來自 API 的 JSON 數據的first name
。 但是,我不斷收到以下錯誤消息: TypeError: Cannot read properties of undefined (reading 'name')
您正在將 json 字符串設置為randomDataJSON
狀態變量,並嘗試使用 JSON 字符串作為對象。 您可以嘗試使用console.log(randomDataJSON)
來確認我的懷疑。
我認為您不應該首先將數據對象轉換為 json,因此setRandomDataJSON(JSON.stringify(userData, null, 2));
將是setRandomDataJSON(userData)
;
function GetData() {
const [randomData, setRandomData] = useState('');
const url = 'https://randomuser.me/api/';
const getData = () => {
axios
.get(`${url}`)
.then((results) => {
const userData = results.data.results;
setRandomData(userData, null, 2);
})
.catch((err) => console.error(err));
};
return (
<div>
<h3>GetData Component</h3>
<pre>{randomData[0].name.first}</pre>
<button onClick={getData}>Get Data</button>
</div>
);
}
export default GetData;
在頁面加載時 axios 不會運行來請求數組,所以當時 randomDataJSON 是一個字符串。 你可以做
const [randomDataJSON, setRandomDataJSON] = useState([]);
在上面你將它設置為一個空數組然后檢查它是否有長度
<pre>{randomDataJSON.length > 0 && randomDataJSON[0].name.first}</pre>
非常感謝大家指出我正確的方向。 我的新代碼如下。 我的問題是我不知道 React 不允許你渲染 Javascript 對象。 為了解決這個問題,我只使用 map() 方法來映射數據並顯示對象中的屬性。
function GetData() {
const [randomDataJSON, setRandomDataJSON] = useState([]);
const url = 'https://randomuser.me/api/';
const getData = () => {
axios
.get(`${url}`)
.then((results) => {
const userData = results.data.results;
setRandomDataJSON(userData);
})
.catch((err) => console.error(err));
};
console.log('It is an', typeof randomDataJSON);
console.log('randomDataJSON is ', randomDataJSON);
return (
<div>
<h3>GetData Component</h3>
{randomDataJSON.map((data) => {
return <p>{data.name.first}</p>;
})}
<button onClick={getData}>Get Data</button>
</div>
);
}
export default GetData;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.