[英]How to map a React functional component
我正在嘗試通過 React.js 代碼顯示單個用戶 JSON API 結果。 這是我在執行console.log()
時得到的 JSON 響應。
{"id":1,"email":"test.k@gmail.com","mobile":+989898989,"name":"testname K","address":"my address here, India","gender":"1","tagline":"Friendly to all"}
但是當我嘗試將其打印為 {singleUserDetail.name} 時,它什么也沒打印。 這里有什么問題?
const [singleUserDetail, setsingleUserDetail] = React.useState('');
const id = user.id;
console.log(id); //getting id here as 1
const getsingleUserDetails = () => {
axios
.get(`http://localhost:3001/user/1`, { withCredentials: true })
.then((response) => {
const singleUserDetail = response.data;
console.log(response.data); //prints the above json reults in console
})
.catch((error) => {
console.log(" error", error);
});
};
React.useEffect(() => {
getsingleUserDetails();
}, []);
return (
<div>
<p>{singleUserDetail.name}</p>
</div>
);
}
singleUserDetail
是您的 state,但您在 axios function 內部分配了一個新變量。 你應該這樣做;
setSingleUserDetail(response.data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.