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

React中英雄列表添加至收藏数组的条件函数失效问题求助

Hey there! Let's work through the issues in your code step by step—there are a few small logical and syntax mistakes causing those frustrating problems:

1. Incorrect check for existing favorites

You're using favorites.includes((heroin) => heroin.id === id) to check if a hero is already saved, but includes() looks for exact value matches, not predicate functions. Use some() instead, which checks if any element passes your test:

if (favorites.some(hero => hero.id === id)) {
  setMessage("hero already in favorites!");
  return; // Exit early so we don't run the rest of the add logic
}

2. Assignment instead of comparison for list length

You wrote favorites.length = 6 which is an assignment (you're setting the length to 6!) instead of a check. Use === to compare values:

if (favorites.length === 6) {
  setMessage("favorites list full!");
  return; // Exit early
}

3. Wrong way to add the correct hero to favorites

Your concat() call is passing a function instead of the actual hero object. First find the matching hero from your heroes array, then add it to favorites:

const heroToAdd = heroes.find(hero => hero.id === id);
const newFavorites = [...favorites, heroToAdd]; // Or favorites.concat(heroToAdd)
setFavorites(newFavorites);

4. Missing early returns lead to overwritten messages

Right now, even if the hero is already in favorites or the list is full, the code still runs the "add to favorites" logic and overwrites your message. Adding return after setting those messages stops the function from continuing.

5. Mismatched property names when rendering

In your heroes.map you're extracting props (likely a typo for name?), but in the favorites map you're trying to access favorite.name. Fix the property name to match your hero object structure:

// Original
const {id, props} = heroin;
// Corrected (assuming your heroes have a `name` field)
const {id, name} = heroin;
return <div key={id}><h1>{name}</h1></div>;

6. Syntax error in component structure

Your heroes.map wasn't closed properly, and the buttons were outside the mapped div—this broke the id scoping. Move the buttons inside each hero's container so they know which hero to target.


Here's the full fixed code with all these changes:

import { useState } from 'react';

// Replace with your actual heroes array (objects should have `id` and `name` fields)
const heroes = [
  { id: 1, name: "Superman" },
  { id: 2, name: "Batman" },
  { id: 3, name: "Wonder Woman" }
];

function HeroCollection() {
  const [favorites, setFavorites] = useState([]); 
  const [message, setMessage] = useState(""); 

  const addToFavorites = (id) => { 
    // Check if hero is already in favorites
    if (favorites.some(hero => hero.id === id)){ 
      setMessage("hero already in favorites!");
      return;
    } 
    // Check if favorites list is full
    if (favorites.length === 6) { 
      setMessage("favorites list full!");
      return;
    }
    // Find the hero to add
    const heroToAdd = heroes.find(hero => hero.id === id);
    // Update favorites array
    const newFavorites = [...favorites, heroToAdd];
    setFavorites(newFavorites); 
    setMessage("item added to favorites!");
  };

  const deleteFavorite = (id) => { 
    const newFavorites = favorites.filter(hero => hero.id !== id); 
    setFavorites(newFavorites); 
    setMessage(""); 
  };

  const clearFavorites = () => {
    setFavorites([]);
    setMessage("");
  };

  return (
    <div>
      {/* Render all heroes with action buttons */}
      {heroes.map(hero => { 
        const {id, name} = hero; 
        return (
          <div key={id} style={{ margin: "1rem 0" }}>
            <h3>{name}</h3>
            <button onClick={() => addToFavorites(id)}>Add to favorites</button> 
            <button onClick={() => deleteFavorite(id)} style={{ marginLeft: "0.5rem" }}>Remove favorite</button>
          </div>
        ); 
      })}

      {/* Favorites section */}
      <div style={{ marginTop: "2rem" }}>
        <button onClick={clearFavorites}>Clear favorites</button> 
        <h4 style={{ color: "#666" }}>{message}</h4> 

        <h2>Your Favorites</h2>
        {favorites.length === 0 ? (
          <p>No favorites added yet!</p>
        ) : (
          favorites.map(favorite => { 
            const {id, name} = favorite; 
            return ( 
              <div key={id}>
                <h3>{name}</h3>
              </div> 
            );
          })
        )}
      </div>
    </div>
  );
}

export default HeroCollection;

内容的提问来源于stack exchange,提问作者Amadeo de la Peña

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 15:02:31