简体   繁体   English

在不覆盖 TypeScript 和 React 中的其他对象的情况下推送数组中的多个对象 - 添加到收藏夹列表

[英]Pushing multiple objects in an array without overwriting other objects in TypeScript & React - Adding to a Favorites list

I am finishing a weather app in TypeScipt and React, and the last feature I need to include is the ability to add a queried location to a favorites list.我正在用 TypeScipt 和 React 完成一个天气应用程序,我需要包含的最后一个功能是能够将查询的位置添加到收藏夹列表中。 This is the second-page "favorites".这是第二页的“收藏夹”。

Using a button on the card displayed when a location is queried sets the favorite state to true.使用查询位置时显示的卡片上的按钮将收藏状态设置为 true。

<button className="add-favorite btn" onClick={() => addToFavoritesHandler()}>Add to Favorites</button>

Though, when searching for a new location, the array gets mutated.但是,在搜索新位置时,数组会发生变异。 And even when attempting to add a new location to your favorites, it only shows that one location, no previous locations.即使尝试将新位置添加到您的收藏夹时,它也只会显示该位置,而不显示以前的位置。

This is where if there is a favorited location is mapped out.如果有最喜欢的位置,则在此处绘制。

      {favorites.length === 0 ? (
        <p> Add locations to favorites! </p>
      ) : (
        favorite &&
        arr?.map((location, id) => {
          return (

I simply want to be able to add multiple locations to the favorites list when pressing the button.我只是希望能够在按下按钮时将多个位置添加到收藏夹列表中。

This function handles the pushing to the array and is drilled down to the button on the queried location.此函数处理对数组的推送,并向下钻取到查询位置上的按钮。

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;
  };

The GitHub Repo - https://github.com/carbondesigned/granular-ai-assignement-weather-app GitHub 存储库 - https://github.com/carbondesigned/granular-ai-assignement-weather-app

Thank you.谢谢你。

I quickly read the code inside the repository and I've noticed that the favorites array isn't keep inside a useState , I think that this is the problem.我很快阅读了存储库中的代码,我注意到favorites数组没有保存在useState ,我认为这就是问题所在。

In this way that array will be recreated on every render.这样,该数组将在每次渲染时重新创建。

If you change with:如果您更改为:

const [favorites, setFavorites] = useState<WeatherType[]>([]);

and, inside the function addToFavoritesHandler you update favorites with:并且,在函数addToFavoritesHandler您可以使用以下内容更新favorites

setFavorites(favorites)

you should make this works.你应该让这个工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM