我有以下JSON,我想映射到MUI卡。我没有得到任何错误信息,但没有显示任何东西。console.log(questionGroups)
仅在更改一些不相关的代码以导致实时重新加载后显示JSON。
const [questionGroups, setQuestionGroups] = useState("");
const fetchQuestionGroups= async () => {
setQuestionGroups(
await fetch(`API_LINK`).then((response) => response.json())
);
console.log(questionGroups);
};
useEffect(() => {
fetchQuestionGroups();
}, []);
...
<Box className={classes.cards}>
{questionGroups?.displaygroups?.IntakeQuestion?.map((group, groupIndex) => {
return (
<Card className={classes.card1}>
<CardHeader title={group.GroupName} />
</Card>
);
})}
</Box>
这是我的JSON示例:
{
"displaygroups": {
"IntakeQuestions": [
{
"GroupId": 11,
"GroupName": "Group 1",
"SizingId": null,
"OwnerName": "Jane Doe",
"Questions": 0,
"Answered": null,
"Validated": null
}
]
}
}
使用&而不是?
<Box className={classes.cards}>
{questionGroups &&
questionGroups.displaygroups &&
questionGroups.displaygroups.IntakeQuestions.map((group, groupIndex) => {
return (
<Card className={classes.card1}>
<CardHeader title={group.GroupName} />
</Card>
);
})}
</Box>
您需要在数据可用时设置状态。
const fetchQuestionGroups= async () => {
const data = await fetch(`API_LINK`)
const temp = response.json()
setQuestionGroups(temp);
console.log(questionGroups);
};