我有一個型別為 select 的 customInput,它的 onChange 正在運行一個 setState。
我的狀態物件看起來像這樣
const [upload, setUpload] = useState({
uploadType: 'files',
selectHeader: [],
defaultFields: [
{
baseField: 'First name',
},
{
baseField: 'Last name',
},
{
baseField: 'Phone number',
},
{
baseField: 'Company',
},
{
baseField: 'Email',
},
]
});
當 onChange 運行時,我成功地將一個新物件添加到 selectHeader 陣列中
{value: firstName, index: 1}
問題是,當用戶為索引 1(或任何索引)處的標頭選擇新值時,我想檢查此陣列中是否存在重復項。
我不確定如何使用 setState 行內執行此操作,并且似乎無法在此示例中找到一個好的執行緒
這是下面選擇型別的 CustomInput
<thead>
<tr>
{
fileContacts.map((contact) => (
<th scope="col" key={fileContacts.indexOf(contact)}>
<WizardInput // this is just a fancy CustomInput at its core
type="select"
defaultValue={"Do not Import"}
tag={CustomInput}
name="selectHeader"
id="selectHeader"
onChange={({ target }) => {
setUpload({...upload, selectHeader: [...upload.selectHeader, {value: target.value, index:fileContacts.indexOf(contact)}]})
// this is adding a duplicate object if the user changes the header value twice.
}}
innerRef={register}
errors={errors}
options={['First Name', 'Last name', 'Phone', 'Email']}
/>
</th>
))}
</tr>
</thead>
uj5u.com熱心網友回復:
為 selectheader 創建一個新變數并過濾該陣列以查找任何重復項(有關任何幫助,請查看此問題如何從物件陣列中洗掉所有重復項?),然后將其傳遞給 setUpload
uj5u.com熱心網友回復:
也許您可以在添加新的之前過濾掉前一個。
setUpload({...upload, selectHeader: [...upload.selectHeader.filter(({value}) => value != target.value), { value: target.value, index:fileContacts.indexOf(contact) }] })
uj5u.com熱心網友回復:
嘗試使用功能更新:
setUpload((upload)=>{
if(upload.selectHeader.some(h => h.value == target.value)) return upload
return {
...upload,
selectHeader: [
...upload.selectHeader,
{
value: target.value,
index:fileContacts.indexOf(contact)
}
]
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/405295.html
標籤:
上一篇:使用Ruby:如何在不回傳我正在測驗的命令的輸出的情況下測驗linux命令是否可用?
下一篇:如何在js中為陣列值設定影片?
