You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Redux+TypeScript+AntD:匹配数组ID时切换收藏图标颜色

解决方案

方法一:直接用数组some方法判断匹配ID

遍历搜索结果时,通过some方法检查当前GIF的ID是否存在于收藏数组中,以此切换图标颜色:

{/* 判断当前GIF是否已被收藏 */}
{
  favorites.some(fav => fav.id === result.id)
    ? <HeartTwoTone twoToneColor="red" />
    : <HeartTwoTone twoToneColor="gray" />
}

方法二:提取收藏ID到Set优化性能

如果收藏数组数据量较大,建议提前把所有收藏的ID提取到Set中,能将每次判断的时间复杂度从O(n)降到O(1),提升性能:

const GifsResult: FC<IGifsResultProps> = ({results}) => {

    const dispatch = useDispatch();
    const favorites = useSelector((state: IFavoriteGifs) => state.favorites);
    
    // 提取所有收藏GIF的ID存入Set
    const favoriteIds = new Set(favorites.map(fav => fav.id));

    const addFavorites = (id: string, src: string) => {
        const data = {
            id: id,
            src: src,
        }
        dispatch({type: "ADD_FAVORITE_GIFS", payload: data})
    }

    return (
        <Row>
            {results.map((result, i) =>
                <Col span={8} key={result.id}>
                    {
                      favoriteIds.has(result.id)
                        ? <HeartTwoTone twoToneColor="red" />
                        : <HeartTwoTone twoToneColor="gray" />
                    }
                    <img
                        src={result.images.fixed_height.url}
                        onClick={()=> addFavorites(result.id, result.images.fixed_height.url)}
                    />
                </Col>
            )}
        </Row>
    );
};

额外优化提示

当前代码仅处理添加收藏,若需要支持点击切换收藏状态,可以修改点击逻辑,先判断是否已收藏,再派发对应action:

const toggleFavorite = (id: string, src: string) => {
  const isFavorite = favoriteIds.has(id);
  if (isFavorite) {
    dispatch({type: "REMOVE_FAVORITE_GIFS", payload: id});
  } else {
    dispatch({type: "ADD_FAVORITE_GIFS", payload: {id, src}});
  }
}

随后将图片的onClick替换为onClick={()=> toggleFavorite(result.id, result.images.fixed_height.url)}即可。

内容的提问来源于stack exchange,提问作者Margarita Logatskaya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 04:05:28