【问题标题】:Pushing multiple objects in an array without overwriting other objects in TypeScript & React - Adding to a Favorites list在 TypeScript 和 React 中推送多个对象而不覆盖其他对象 - 添加到收藏夹列表
【发布时间】:2021-09-26 11:19:19
【问题描述】:

我正在使用 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

谢谢。

【问题讨论】:

    标签: javascript arrays reactjs typescript api


    【解决方案1】:

    我快速阅读了存储库中的代码,发现favorites 数组没有保留在useState 中,我认为这就是问题所在。

    这样,数组将在每次渲染时重新创建。

    如果你改变:

    const [favorites, setFavorites] = useState&lt;WeatherType[]&gt;([]);

    并且,在函数 addToFavoritesHandler 中,您将 favorites 更新为:

    setFavorites(favorites)

    你应该让它工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-13
      • 2022-01-20
      • 1970-01-01
      • 2021-07-16
      • 2021-10-08
      • 1970-01-01
      • 2015-06-25
      • 1970-01-01
      相关资源
      最近更新 更多