[英]Pushing multiple objects in an array without overwriting other objects in TypeScript & React - Adding to a Favorites list
我正在用 TypeScipt 和 React 完成一个天气应用程序,我需要包含的最后一个功能是能够将查询的位置添加到收藏夹列表中。 这是第二页的“收藏夹”。
使用查询位置时显示的卡片上的按钮将收藏状态设置为 true。
<button className="add-favorite btn" onClick={() => addToFavoritesHandler()}>Add to Favorites</button>
但是,在搜索新位置时,数组会发生变异。 即使尝试将新位置添加到您的收藏夹时,它也只会显示该位置,而不显示以前的位置。
如果有最喜欢的位置,则在此处绘制。
{favorites.length === 0 ? (
<p> Add locations to favorites! </p>
) : (
favorite &&
arr?.map((location, id) => {
return (
我只是希望能够在按下按钮时将多个位置添加到收藏夹列表中。
此函数处理对数组的推送,并向下钻取到查询位置上的按钮。
const [favorite, setFavorite] = useState(true);
let favorites: WeatherType[] = [];
// Easier readability
let location = weatherData;
// Pushing the favorite location into the favorite array
const addToFavoritesHandler = () => {
setFavorite(true);
if (location && favorite && !favorites.find((o) => o === location)) {
favorites.push(location);
}
return favorites;
};
GitHub 存储库 - https://github.com/carbondesigned/granular-ai-assignement-weather-app
谢谢你。
我很快阅读了存储库中的代码,我注意到favorites
数组没有保存在useState
,我认为这就是问题所在。
这样,该数组将在每次渲染时重新创建。
如果您更改为:
const [favorites, setFavorites] = useState<WeatherType[]>([]);
并且,在函数addToFavoritesHandler
您可以使用以下内容更新favorites
:
setFavorites(favorites)
你应该让这个工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.