[英]API won't return data
當我在顯示特定配置文件的數據的頁面中時,我試圖調用 API。
網址如下: localhost:8000/profile/223
API 也需要調用api/profile/223
我試圖調用 API 的方式是:
const ProfileLayout = () => {
const [profileId, setProfileId] = useState();
useEffect(() => {
fetch('api/profile/id')
.then(result => {
setProfileId(result.id);
});
}, [id])
};
Fetch 要求您在使用數據之前從 Response 對象返回數據的格式。 使用response.json()
從您的請求中獲取 JSON。
就像提到的@Adriana6 一樣,將/
添加到 URL 的開頭。
使用profileId
將值注入 URL 字符串。
useEffect(() => {
fetch('/api/profile/${profileId}')
.then(response => response.json())
.then(result => {
setProfileId(result.id);
});
}, []);
我在 React.js 方面沒有很多經驗,但是通過閱讀這篇關於如何使用 React Hooks 發出fetch
請求的文章,我學會了如何做到這一點。 我建議你也研究一下。
請在您的 fetch 函數參數中寫入完整的 url,如localhost:8000/profile/${id}
。 然后解析為json。
另一方面,您沒有任何 id 字段。 因此,在 useEffect 中使用 id 根本不會被觸發。 如果您希望在頁面加載時觸發它,請使用
useEffect(() => {
// fetch
}, [])
代替
useEffect(() => {
// fetch
}, [id])
或者您可以使用profileId
更改id
。 在這種情況下,您必須在獲取配置文件數據之前檢查profileId
是否為真(非空)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.