我遇到了一個問題,我試圖解決它很多時間但無法解決它,請嘗試修復我的錯誤。如果您有任何疑問,請隨時提問。
用戶資料.js
這是 userdata.js 檔案,我想在其中加載后端資料庫中的所有資料
import React, { useEffect, useState } from "react";
import { Link,useParams } from "react-router-dom";
import Axios from 'axios';
const UserData = () => {
const [users, setUser] = useState({
title : "",
description : ""
});
const {id} = useParams();
useEffect(() => {
AllUsers();
}, []);
const AllUsers = async () => {
const res = await Axios.get(`http://localhost:3000/${id}`);
console.log(res.data);
setUser(res.data)
};
return (
<div>
<div className="container">
<table className="table table-hover table-bordered mt-5">
<thead>
<tr>
{/* <th scope="col">No</th> */}
<th scope="col">Title</th>
<th scope="col">Details</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
{users.map((user, index) => (
<tr key={index}>
<th scope="row">{user.id}</th>
<td>{user.title}</td>
<td>{user.description}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
};
export default UserData;
uj5u.com熱心網友回復:
users在我看來是一個物件,而不是一個陣列。該map()函式僅存在于Array的原型上,因此您不能在users物件上呼叫它。你的意思是這樣初始化users嗎?
const [users, setUser] = useState([{
title : "",
description : ""
}]);
uj5u.com熱心網友回復:
該map方法是在陣列上而不是在物件上定義的。讓我們看看你的代碼
const [users, setUser] = useState({
title : "",
description : ""
});
在UserData組件中,您定義了一個具有標題和描述屬性的物件狀態。users具有這些屬性的物件也是如此。因此,當您嘗試在users物件上應用 map 時它會失敗,因為 map 不是在物件上定義的函式。
相反,如果您想擁有具有這兩個屬性的用戶陣列,您可以按如下方式宣告狀態
const [users, setUser] = useState([{
title : "",
description : ""
}]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/377422.html
上一篇:C#獲取自定義屬性擴展方法
