[英]Reactjs : TypeError: Cannot read property 'map' of undefined
我一直在研究那個 React 項目,並且一直在使用 axios 從我的后端獲取數據。 我多次收到 (TypeError: Cannot read property 'map' of undefined) 錯誤,我嘗試了多次修復,但沒有希望修復。 我添加了一個用於加載的鈎子以確保在渲染之前存在數據,但是如果我在頁面之間返回和第四個 go 我收到相同的錯誤
這是我的代碼:
function Developer(props) {
const [data, setData] = useState();
const [loading , setLoading] = useState(true)
const [error, setError] = useState();
var id = props.match.params.id
var location = props.match.params.location
useEffect(() => {
axios(`http://localhost:5000/api/${location}/${id}`)
.then((response) => {
setData(response.data);
})
.catch((error) => {
console.error("Error fetching data: ", error);
setError(error);
})
.finally(() => {
setLoading(false);
});
}, []);
if (loading) return "Loading...";
if (error) return "Error!";
return (
<div>
<h1>{data.Developer}</h1>
<ul>
{
data.Projects.map((project) => (<li key = {project._id}>
<a href= {`/${location}/${id}/${project._id}`}>{project.Project}</a></li> ))
}
</ul>
</div>
)}
在對其進行 map 之前,您應該檢查數據屬性的性質。
{
data && data.Projects.length !== 0 &&
data.Projects.map((project) => (<li key = {project._id}>
<a href= {`/${location}/${id}/${project._id}`}>{project.Project}</a></li> ))
}
我建議你使用 javascrip fetch
我自己多次遇到這個錯誤。
首先檢查您從 api 獲得的數據是否是 javascript 對象的數組
這是一個簡單的解決方案。
{data ? data.Projects.map((project) => (<li key={project._id}>
<a href={`/${location}/${id}/${project._id}`}>{project.Project}</a></li>)) :<div>Loading..</div>}
所以我在這里所做的是使用三元運算符,它將檢查數據 state 是否有數據,如果有它將顯示數據,否則它將顯示“正在加載...”
Axios 需要一些時間來獲取和設置數據,但頁面在此之前呈現,這就是為什么它顯示無法讀取未定義的屬性“地圖”
返回的數據可能不包含您需要的內容。
嘗試打印出返回的數據
axios(`http://localhost:5000/api/${location}/${id}`)
.then((response) => {
console.log(response.data);
setData(response.data);
})
它可能是一個有效的響應,但不包含該變量data.Projects
。 如果您想處理該值的缺失,您可以使用以下內容:
(data.Projects || []).map(...)
這樣,如果data.Projects
是假的,它將被一個空數組替換,它會調用[].map(...)
。
如前所述,您的 setLoading(true) 要求。
function Developer(props) {
const [data, setData] = useState();
const [loading , setLoading] = useState(true)
const [error, setError] = useState();
var id = props.match.params.id
var location = props.match.params.location
useEffect(() => {
// ooh look, we are in a loading state here, cause the data hasn't come back from the server at this point.
setLoading(true);
axios(`http://localhost:5000/api/${location}/${id}`)
.then((response) => {
setData(response.data);
// awesome, data has returned from the server, we aren't loading anymore, but the finally block handles that scenario for us.
})
.catch((error) => {
console.error("Error fetching data: ", error);
setError(error);
})
.finally(() => {
setLoading(false);
});
}, []);
if (loading) return "Loading...";
if (error) return "Error!";
return (
<div>
<h1>{data.Developer}</h1>
<ul>
{
data && data.Projects.length && data.Projects.map((project) => (<li key = {project._id}>
<a href= {`/${location}/${id}/${project._id}`}>{project.Project}</a></li> ))
}
</ul>
</div>
)}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.