我的.map函数出错了。我相信问题比这更大,因为有时我的fetch会以未定义的方式返回。我一直在研究解决方案,但没有找到任何给我解决办法的办法。
Props -是具有用户ID的登录用户对象。
discBag控制台有时作为数组,但也会作为未定义的控制台。这就是我认为我的问题发生的地方。我已经研究过组件安装,但是我与类和super()语法混淆了。
我对web开发很陌生,这是我的第一个堆栈溢出问题。任何解决方案或对解决方案的指导,我们将不胜感激!
function DiscBag(props) {
const [loading, setLoading] = useState(true);
const [discBag, setDiscBag] = useState([]);
const userID = props.user.user.id;
console.log(userID)
console.log(discBag)
const getDiscs = async () => {
try {
const response = await fetch(`/users/${userID}`)
const data = await response.json()
setLoading(false)
setDiscBag(data.discBag)
} catch (error) {
console.log(error)
}
};
useEffect(() => {
getDiscs();
}, []);
if (loading) {
return <div> ....loading bro</div>;
}
return (
<div className="child">
<p>not loading</p>
{discBag.map((index, discs) => (
<div className="discs" key={index}>
{discs}
</div>
))}
</div>
);
}发布于 2022-10-17 22:12:17
根据您的描述,似乎有时对服务器的调用不返回data.discBag值,这会导致discBag状态为空(并且map函数只能在数组上运行,以下是问题的修正:
{discBag?.map((discs, index) => (发布于 2022-10-17 22:13:22
你能试试{discBag.map((discs, index) => ...吗?第一个是元素,第二个是下面的指数;
array.map((currentElement, index) => { something... })
https://stackoverflow.com/questions/74103751
复制相似问题