[英]remove value from form within component
我試圖讓用戶從當前設置中刪除值。
我有一系列用戶可以擁有的設置值,這些值以葯丸格式顯示,他們可以單擊 X 刪除,即,
export default function Pill({ value, handleChange }) {
// const [times, setTimes] = useState([]);
return (
<div className="bg-gray-600 text-white text-xs px-2 py-0.5 w-max-content rounded-lg align-middle mr-1 mb-1">
{value}
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="inline-block align-middle cursor-pointer"
onClick={() => handleChange(value, "remove")}
>
<line x1="18" y1="6" x2="6" y2="18" />
<line x1="6" y1="6" x2="18" y2="18" />
</svg>
</div>
);
}
這用作如下組件,
{substanceDetails &&
substanceDetails.map((subst) => (
<Pill
registerInput={register}
optionLabel="substance"
value={subst.substance}
key={subst.substance}
optionName="substance"
allOptions={["Dexamphetamine", "Ritalin"]}
handleChange={handleChange}
/>
))}
鑒於需要更改的句柄更改,但它看起來像這樣,
const handleChange = (value, mode) => {
let updatedValues = values;
if (mode === 'remove') {
updatedValues = values.filter((elem) => elem !== value);
} else if (!updatedValues.includes(value)) updatedValues = [...values, value];
setValues(updatedvalues);
};
您正在修改handleChange
函數中的狀態:
const handleChange = (value, mode) => {
let updatedValues = values; //takes the reference to state variable
if (mode === 'remove') {
updatedValues = values.filter((elem) => elem !== value); //mutation
} else if (!updatedValues.includes(value)) updatedValues = [...values, value];
setValues(updatedvalues);
};
你可以使用這樣的東西:
const handleChange = (value, mode) => {
if(mode==="remove") setValues(vals => vals.includes(value) ? vals.filter(v => v !== value) : [...vals, value])
};
如果您的數組元素不是原始值, .includes()
將不會按預期工作。 在這種情況下,您可以使用.find()
或.some()
:
為簡單起見,按字段duration
過濾的示例:
const handleChange = (value, mode) => {
if(mode==="remove") setValues(vals => vals.find(v=> v.duration === value.duration) ? vals.filter(v => v.duration !== value.duration) : [...vals, value])
};
閱讀您的代碼后,我發現主要問題可能不是突變問題,而是您沒有很好地管理狀態。
首先,您的substanceDetails
應該存儲在YourSubstanceListComponent
組件中,而不是存儲在您的Pill
組件中,就像這樣。 這是您的第一種方法不起作用的主要原因。
// in YourSubstanceListComponent
const YourSubstanceListComponent = () = {
const [values, setValues] = useState([]);
const handleChange = (value, mode,optionName) => {
// Should call `setValues` in this function
const newValues = [];// TODO
setValues(newValues);
}
return (
<>
{values.map(v => <Pill {...otherPillProps} value={v.substance} />)}
</>
)
}
然后,您的handleChange
應該放在YourSubstanceListComponent
。 原因是您可能不想將setValues
傳遞給您的Pill
組件。
接下來是關於獲取新的刪除值項目的部分。 根據文檔:
他們不會修改原始數組。 所以你可以像在你的代碼中一樣使用它們,它應該可以工作。
但是,我在您的代碼中發現了更多問題,我認為您應該再次檢查。
map
(當元素數量不變時)或filter
(當元素數量發生變化時)。 除了map
和filter
,我這輩子很少使用任何其他方法。handleChange
函數中,我沒有看到optionName
變量。 它從何而來? 也許你沒有更新你的Pill
組件。@ShinaBR2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.