React 中重复添加已删除项失效的解决方案

11次阅读

React 中重复添加已删除项失效的解决方案

react 列表操作中,因 `

react 中, 的当前值仍为 “Chicken Breast”,此时再次点击同一选项,浏览器不会触发 onChange,id 变量也不会更新——导致后续 Add 按钮逻辑中 id === food[i].name 始终为 false,新增失败。

✅ 正确做法:使用受控组件 + 清空 select 值

import foods from 'json/foods';  const [meal, setMeal] = useState([]); const [selectedFoodName, setSelectedFoodName] = useState(''); // ✅ 受控状态  const handleAdd = () => {   if (!selectedFoodName) return;    const foodToAdd = foods.find(food => food.name === selectedFoodName);   if (!foodToAdd) return;    // 防重:检查是否已存在同名项(推荐用 id 判断更可靠)   if (meal.some(item => item.id === foodToAdd.id)) {     alert(`"${foodToAdd.name}" 已在列表中`);     return;   }    setMeal(prev => [...prev, foodToAdd]);   setSelectedFoodName(''); // ✅ 添加后立即清空 select };  const handleRemove = (id) => {   setMeal(prev => prev.filter(item => item.id !== id)); };

对应 jsX 更新如下:

{/* 渲染列表 */} {meal.map((item) => (

{item.name}

Protein: {item.protein}

Fats: {item.fats}

Carbs: {item.carbs}

handleRemove(item.id)} />

))}

text=ZqhQzanResources