TypeError:无法读取未定义读取‘长度’的属性[重复]
2022-07-20
7094
从 API 获取数据时,我在 equipmentExercises 块中收到此错误。我已经检查了数据类型,它是一个数组。 并且 equipmentExercises.length 显示未定义的数据类型。
const SimilarExercises = ({ targetMuscleExercises, equipmentExercises }) => {
console.log(equipmentExercises);
return (
<Box sx={{ mt: { lg: '100px', xs: '0px' } }}>
<Typography
sx={{ fontSize: { lg: '44px', xs: '25px' }, ml: '20px' }}
fontWeight={700}
color="#000"
mb="33px"
>
Similar <span style={{ color: '#FF2625', textTransform: 'capitalize' }}>Target Muscle</span> exercises
</Typography>
<Stack direction="row" sx={{ p: 2, position: 'relative' }}>
{targetMuscleExercises.length !== 0 ? <HorizontalScrollbar data={targetMuscleExercises} /> : <Loader />}
</Stack>
<Typography
sx={{ fontSize: { lg: '44px', xs: '25px' }, ml: '20px', mt: { lg: '100px', xs: '60px' } }}
fontWeight={700}
color="#000"
mb="33px"
>
Similar <span style={{ color: '#FF2625', textTransform: 'capitalize' }}>Equipment</span> exercises
</Typography>
<Stack direction="row" sx={{ p: 2, position: 'relative' }}>
**{equipmentExercises.length !== 0 ? <HorizontalScrollbar data={equipmentExercises} /> : <Loader />}**
</Stack>
</Box>
);
};
2个回答
这是因为您的
equipmentExercises
和
targetMuscleExercises
可能一开始就为空。
您可以通过添加如下检查来修复此问题:
equipmentExercises?.length !== 0
或
equipmentExercises && equipmentExercises.length !== 0
sakshya73
2022-07-20
您可以传入一个数组的字符串,而不是数组。您能用
typeof
进行验证吗?
ihateprogramming
2022-07-20