如何基于已选值过滤对象数组?删除证书后状态异常求助
问题解决方案
核心问题出在状态更新逻辑和可选列表的计算方式上,以下是具体修复方案:
1. 修正可选选项计算逻辑
确保可选列表始终从原始数据源中排除已选项,每次组件渲染时动态计算,这样删除证书后对应的选项会自动恢复:
const availableOptions = FirstAidTypeSource.filter( item => !selectedCertificates.some(cert => cert.Value === item.Value) );
2. 修复删除证书逻辑
通过证书的Value属性精准删除对应项,避免索引操作导致的状态不一致:
const handleDelete = (value) => { setSelectedCertificates(prev => prev.filter(cert => cert.Value !== value)); };
3. 修正Add按钮显示条件
按钮显示直接基于可选列表的长度,只要还有可选选项就展示:
{availableOptions.length > 0 && ( // 下拉选择框和Add按钮代码 )}
完整修复后的核心代码
import { useState } from "react"; const FirstAidTypeSource = [ { Name: "First Aid", Value: "First Aid" }, { Name: "Senior First Aid", Value: "Senior First Aid" }, { Name: "Anaphylaxis Certificate", Value: "Anaphylaxis Certificate" }, { Name: "Asthma Certificate", Value: "Asthma Certificate" } ]; export default function App() { const [selectedCertificates, setSelectedCertificates] = useState([]); const [currentSelection, setCurrentSelection] = useState(""); // 动态计算可选证书 const availableOptions = FirstAidTypeSource.filter( (item) => !selectedCertificates.some((cert) => cert.Value === item.Value) ); const handleAdd = () => { if (!currentSelection) return; const selectedItem = FirstAidTypeSource.find( (item) => item.Value === currentSelection ); setSelectedCertificates((prev) => [...prev, selectedItem]); setCurrentSelection(""); }; const handleDelete = (value) => { setSelectedCertificates((prev) => prev.filter((cert) => cert.Value !== value) ); }; return ( <div className="App"> <h1>First Aid Certificates</h1> {/* 已选证书列表 */} <div> {selectedCertificates.map((cert, index) => ( <div key={index}> <span>{cert.Name}</span> <button onClick={() => handleDelete(cert.Value)}>Delete</button> </div> ))} </div> {/* 新增证书区域 */} {availableOptions.length > 0 && ( <div> <select value={currentSelection} onChange={(e) => setCurrentSelection(e.target.value)} > <option value="">Select a certificate</option> {availableOptions.map((item) => ( <option key={item.Value} value={item.Value}> {item.Name} </option> ))} </select> <button onClick={handleAdd} disabled={!currentSelection}> Add Certificate </button> </div> )} </div> ); }
修复说明
- 可选列表动态计算:每次渲染时从原始数据源过滤已选项,删除操作后自动恢复对应可选值
- 精准删除:通过唯一标识
Value删除,避免索引操作引发的状态混乱 - 按钮显示逻辑:直接关联可选列表长度,逻辑更直观准确
内容的提问来源于stack exchange,提问作者webcoder
相关产品推荐
相关产品推荐

