我正在设计一个“喜欢”按钮,当单击该按钮时,将使用单击的项目更新收藏夹组件。我在App.js中声明了一个状态变量,以使其正常工作。
我已经将状态更新函数传递到我的ProductCard中,以便在单击项目对象时获取该对象,然后将状态变量传递到我的ImageGrid,因为这是我想要Map状态并显示对象的位置。
我的问题是,当我将状态传递给UserProfile组件时,它是未定义的。
有人能告诉我问题出在哪吗?
- 我缩短了App.js并删除了对象数组以进行演示 *
APP JS
//State
const [favourites, setFavourites] = useState([
{
type: 'peppermint Latte',
cafe: 'Nomad',
location: 'Barcelona',
price: '$2',
img: Coffee4,
index: 4,
}
]);
// Get items for favourites
function getItem (item) {
setFavourites([favourites, item])
// console.log(favourites)
}
useEffect(() => {
getItem()
}, [])
return (
<>
<Router>
<Routes>
<Route path='/' element={<LoginPage/>} />
<Route path='/profile' element={<UserProfile images={images} getItem={getItem}/>} favourites={favourites} />
</Routes>
</Router>
</>
);
}
export default App;
import React from 'react';
import FavoriteIcon from '@mui/icons-material/Favorite';
const ProductCard = ({images, getItem}) => {
return (
<div className="flex flex-wrap mt-44 sm:mt-60 sm:pl-32 sm:pr-32">
{images.map((item, index) => (
<div key={item.index} className="w-full sm:w-1/2 lg:w-1/3 p-4">
<div className="rounded-lg shadow-md bg-neutral-900 text-white">
<img src={item.img} alt="Product Image" className="w-full h-96 rounded-t-lg" />
<div className="p-4">
<div className='flex justify-between'>
<h2 className="text-lg font-medium">{item.type}</h2>
<h2 className="text-lg font-medium text-yellow-400">{item.location}</h2>
</div>
<div className='flex justify-between'>
<h3 className="text-lg font-medium">{item.cafe}</h3>
<h3 className="text-lg font-medium" onClick={() => getItem(item)}><FavoriteIcon sx={{ stroke: "yellow", strokeWidth: 1 }} className="text-red-600 text-xl"/></h3>
</div>
<h3 className="text-sm font-medium text-white">{item.price}</h3>
</div>
</div>
</div>
))}
</div>
);
};
export default ProductCard;
const ImageGrid = ({images, favourites}) => {
// console.log(favourites)
return (
<div className='fixed bg-neutral-900 w-full'>
<p className='m-2 text-white text-center'>Favourites</p>
<div className="flex flex- justify-center ">
{favourites && favourites.length>0 ?
favourites.map((item) => (
<div>
<img src={item.img} className="w-24 h-24 sm:w-32 sm:h-32 rounded-full m-2" alt="Image 1" />
<span className='text-white flex justify-center'>{item.cafe}</span>
</div>
)) : <p>No favourites yet</p>}
</div>
</div>
);
};
export default ImageGrid;
2条答案
按热度按时间mspsb9vt1#
在您的示例中,可能存在复制粘贴问题,但看起来到UserProfile的路由是未关闭的语法错误。
而不是:
它看起来应该是:
c6ubokkw2#
getItem
应该扩展旧的favorites
。当前它将状态设置为两个值的数组,旧的favorites
和item