React遍历分类时无法正确传递对应分类items prop问题求助
Hey Stephen, let's walk through the most common reasons this happens and how to fix it—even without seeing your full code and JSON structure.
1. Verify Your Filtering Logic is Correct
The most likely culprit is that you're passing the entire items array to each category component instead of filtering it to only items linked to that category.
For example, if you have a list of categories and a full list of allItems, you need to filter allItems for each category using a matching identifier (like category.id and item.categoryId):
{categories.map(category => { // Filter items to only those belonging to the current category const categorySpecificItems = allItems.filter( item => item.categoryId === category.id ); return ( <CategoryList key={category.id} // Always use a unique, stable key (not index!) category={category} items={categorySpecificItems} // Pass the filtered array, not allItems /> ); })}
Double-check that your JSON structure uses matching keys (e.g., category has id, items have categoryId—not category_id or groupId which would break the filter).
2. Check for Incorrect Component Keys
If you're using an index as the key prop instead of a unique category identifier, React might reuse components incorrectly, making it look like all items are being passed to every category.
Bad practice (can cause stale data):
{categories.map((category, index) => ( <CategoryList key={index} ... /> ))}
Good practice (stable, unique key):
{categories.map(category => ( <CategoryList key={category.id} ... /> ))}
3. Debug with Console Logs
Add quick console logs to confirm your filtering is working as expected. This will tell you if the issue is with the filter logic or something else:
{categories.map(category => { const filteredItems = allItems.filter(item => item.categoryId === category.id); console.log(`Category: ${category.name} | Items count: ${filteredItems.length}`); return <CategoryList key={category.id} items={filteredItems} ... />; })}
If the log shows the correct number of items per category but React DevTools still shows 667, the issue might be inside your CategoryList component (e.g., it's using a global items state instead of the passed items prop).
4. Ensure No State Pollution
Make sure your CategoryList component isn't accidentally referencing a global items array instead of the items prop passed to it. For example, avoid this inside the component:
// ❌ Bad: Using global state instead of the prop const [items, setItems] = useState(allItems);
Instead, directly use the prop:
// ✅ Good: Using the passed prop const CategoryList = ({ items, category }) => { return ( <div> <h2>{category.name}</h2> <ul> {items.map(item => <li key={item.id}>{item.name}</li>)} </ul> </div> ); };
内容的提问来源于stack exchange,提问作者Stephen

