[英]React array is populated with items, however, upon trying to do the .map function, it says .map is not a function
我试图将数组的项目渲染到屏幕上并显示这些项目。 所以我做了 .map function。但是,当我执行 map function 时,它说 cars.map 不是 function。我控制台记录了汽车阵列中的项目,它确实被填充了。 我在这里做错了什么吗? 任何建议都有帮助! 谢谢!
const [cars, setCars] = useState([]);
以及设置汽车阵列的位置:
useEffect(async () => {
const result = await initCarsInfo();
setCars(result);
}, []);
console.log(cars);
这是汽车的控制台日志
{cars: Array(2)}cars: Array(2)0: {name: 'Lexus ES', year: 1995, totalMiles: 200000, …}1: {name: 'Kia Sonota', year: 2005, totalMiles: 250000, …}length: 2[[Prototype]]: Array(0)[[Prototype]]: Object
我在哪里映射它:
const getAssetMenuItems = () => {
{cars && cars.map(carObj => {
return (
<MenuItem value="car1">
<span style={{ marginLeft: '10px' }}>
<Typography className={classes.carsName}>{carObj.name}</Typography>
<Typography>{carObj.year}</Typography>
</span>
</MenuItem>
)
})}
};
我在控制台中记录了汽车阵列中的项目,它确实被填充了——这是真的,但不是你所期望的。
您的initCarsInfo
中的cars
cars
object,而不是直接返回数组。
请注意,您的控制台日志显示cars
的值为 object: {cars: Array(2)}
。
设置 state 时,您需要从结果中访问该属性:
useEffect(async () => {
const result = await initCarsInfo();
setCars(result.cars);
}, []);
你需要这样打电话:
useEffect(async () => {
const result = await initCarsInfo();
setCars(result.cars);
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.