//I fetched the data here using context Api
const [allProfiles, setAllProfiles] = useState("");
const fetchAllProfiles = async () => {
const res = await axios.get("http://localhost:5000/api/all-profiles");
setAllProfiles(res.data);
};
//I receive the data here in the frontend.
import Image from "next/image";
import React, { useContext, useEffect } from "react";
import Layout from "@/components/Layout";
import MyContext from "@/store/MyContext";
function Sellers() {
const { allProfiles, fetchAllProfiles } = useContext(MyContext);
useEffect(() => {
fetchAllProfiles();
}, []);
return (
<Layout>
<div className="container flex justify-center mx-auto pt-16">
<div>
<p className="text-gray-500 text-lg text-center font-normal pb-3">
SELLERS
</p>
<h1 className="thesellermaintext">
View Buyers Profile Here, You Might Be Lucky To Find Your Dream Car
Too.
</h1>
</div>
</div>
{allProfiles.map((profiles, i) => (
<div className="w-full bg-gray-100 px-10 pt-10">
<div className="container mx-auto">
<div className="thesellerbg">
<div className="sellersimagebg">
<div className="rounded overflow-hidden shadow-md bg-white">
<div className="absolute -mt-20 w-full flex justify-center">
<div className="h-32 w-32">
<Image
width={400}
height={400}
src="/assets/images/d17.jpg"
alt="profile"
className="sellersimage"
/>
</div>
</div>
<div className="px-6 mb-8 mt-16">
<div className="font-bold text-3xl text-center pb-1">
{allProfiles.name}
</div>
<p className="text-gray-800 text-sm text-center">
{profiles.businessStatus}
</p>
<p className="text-center text-gray-600 text-base pt-3 font-normal">
{profiles.description}
</p>
</div>
</div>
</div>
</div>
</div>
</div>
))}
</Layout>
);
}
export default Sellers;
我在這里面臨的問題是,每當我通過單擊按鈕(指向此路線的按鈕)獲取資料時,資料都會成功獲取,但是每當我自己在瀏覽器中直接輸入鏈接地址時,它都會保持當我 console.log 資料時回傳空字串(像這樣<empty string>),并不斷拋出錯誤說“allCars.map 不是函式。
uj5u.com熱心網友回復:
你嘗試用這樣的空陣列初始化“allProfiles”:
const [allProfiles, setAllProfiles] = useState([]);
空字串似乎與來自 api 回應的陣列不同
uj5u.com熱心網友回復:
當頁面加載allProfiles為空時,它無法被映射。您應該首先檢查allProfiles是否存在,然后再進行映射。
{allProfiles ? allProfiles.map((profiles, i) => (
<div>{profiles.name}</div>
)) : <div>Loading...</div>}
uj5u.com熱心網友回復:
const fetchAllProfiles = async () => {
const res = await axios.get("http://localhost:5000/api/all-profiles",{
headers: {
"Content-type": "application/json",
},
});
setAllProfiles(res.data);
};
嘗試在獲取請求的標頭中添加內容型別
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/425520.html
標籤:javascript 节点.js 反应 axios 下一个.js
上一篇:如何重置嵌套物件的值?
