我正在從我的 API 加載一些資料,它成功回傳,但 React 之后沒有渲染卡片。
export default function Subjects() {
const userApi = useUserService();
const auth = useRecoilValue(AuthAtom);
const [loading, setLoading] = React.useState<boolean>(true);
const [subjects, setSubjects] = React.useState<Subject[]>();
React.useEffect(() => {
userApi.getSubjects(auth?.userId ?? 0).then((value: Subject[]) => {
setSubjects(value);
setLoading(false);
});
}, []);
return (
<Box display="flex" flexDirection="row" alignItems="center">
{!loading &&
subjects?.map(function (subject: Subject) {
<Card key={subject.name}>
<CardActionArea>
<CardContent>{subject.name}</CardContent>
</CardActionArea>
</Card>;
})}
</Box>
);
}
userApi.getSubjects 回傳一個主題陣列。
uj5u.com熱心網友回復:
您不會在.map回呼中回傳任何內容,因此您的組件不會呈現任何內容。要解決這個問題:
subjects?.map(function (subject: Subject) {
// add the return statement like below.
return (
<Card key={subject.name}>
<CardActionArea>
<CardContent>{subject.name}</CardContent>
</CardActionArea>
</Card>
);
})}
uj5u.com熱心網友回復:
您在體內的函式不回傳任何內容。嘗試這個:
return (
<Box display="flex" flexDirection="row" alignItems="center">
{!loading &&
subjects?.map(function (subject: Subject) {
return (
<Card key={subject.name}>
<CardActionArea>
<CardContent>{subject.name}</CardContent>
</CardActionArea>
</Card>;
);
})}
</Box>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/352875.html
上一篇:ReactAPI單個產品未呈現
