如何在React组件中渲染食材列表,无需逐一编写strIngredient1至strIngredient20?
Ugh, dealing with those numbered strIngredientN and strMeasureN fields is such a tedious chore—no need to write 20 lines of repetitive code. Here's a clean, scalable approach to handle this in React:
Step 1: Extract Valid Ingredients into an Array
First, we'll loop through the range 1 to 20, check if each ingredient field has a non-empty value, and pair it with its corresponding measure. This way, we only keep the ingredients that actually exist in the data.
// Assuming you've already fetched the meal data (from your JSON snippet) const meal = meals[0]; // Initialize an empty array to hold our formatted ingredients const ingredients = []; // Loop from 1 to 20 to cover all possible ingredient fields for (let i = 1; i <= 20; i++) { const ingredientName = meal[`strIngredient${i}`]; const ingredientMeasure = meal[`strMeasure${i}`]; // Only add the ingredient if it has a non-empty value (skip null/empty strings) if (ingredientName && ingredientName.trim()) { ingredients.push({ name: ingredientName, amount: ingredientMeasure || '' // Fallback to empty string if measure is missing }); } }
Step 2: Render the Ingredients Array
Now that we have a clean array of ingredients, we can use React's map() function to render them as a list—no repetitive JSX needed!
export default function MealIngredients({ meal }) { // The ingredient extraction code from Step 1 goes here const ingredients = []; for (let i = 1; i <= 20; i++) { const ingredientName = meal[`strIngredient${i}`]; const ingredientMeasure = meal[`strMeasure${i}`]; if (ingredientName && ingredientName.trim()) { ingredients.push({ name: ingredientName, amount: ingredientMeasure || '' }); } } return ( <div className="meal-ingredients"> <h3>Ingredients</h3> <ul> {ingredients.map((ingredient, index) => ( <li key={index}> {/* Only show the measure if it exists */} {ingredient.amount && <span>{ingredient.amount} </span>} {ingredient.name} </li> ))} </ul> </div> ); }
Bonus: More Concise Version with Array.from
If you prefer a more functional style, you can use Array.from to create the ingredients array in one line (plus a filter to remove empty entries):
const ingredients = Array.from({ length: 20 }, (_, i) => { const num = i + 1; const name = meal[`strIngredient${num}`]; const amount = meal[`strMeasure${num}`]; // Return the ingredient object only if the name is non-empty return name && name.trim() ? { name, amount: amount || '' } : null; }).filter(Boolean); // Filter out any null entries
This approach works seamlessly even if some ingredient fields are missing or empty—you'll only get the valid ingredients in your rendered list.
内容的提问来源于stack exchange,提问作者Ejirooghene Oke

