[英]How to remove nested object by Id from Formik?
I am trying to remove an entire flight item from a nested array.我正在尝试从嵌套数组中删除整个航班项目。 I've tried setFieldvalue.
我试过 setFieldvalue。 Whenever I find a specific ID, i'd like to remove the entire item from Formik.
每当我找到特定 ID 时,我都想从 Formik 中删除整个项目。 For some reason the internet is sparse with solutions, even on SO.
出于某种原因,互联网上的解决方案很少,即使是在 SO 上。
console.log("Formik", formik.values.flightsById);
for (let item in formik.values.flightsById){
if(item === 'EF_700001132'){
console.log("it's here: ", item)
// React.useEffect(() => () => formik.setFieldValue(item, undefined), [])
//formik.values.flightsById.remove
}
}
console.log("Formik after del: ", formik.values.flightsById);
Some feedback:一些反馈:
flightsById
as a "nested array", but judging from your screenshot it's an objectflightsById
称为“嵌套数组”,但从您的屏幕截图来看,它是一个对象setFieldValue()
to update flightsById
, nice work 😉setFieldValue()
更新flightsById
,您的想法是正确的, flightsById
好😉if
statement will trigger an error because it breaks the rules of hooksif
语句中放置 useEffect 会触发错误,因为它违反了钩子规则EF_700001132
from the flightsById
, you will need to clone flightsById
except for that key, and then pass it into setFieldValue()
.flightsById
完全删除它们的键EF_700001132
,则需要克隆除该键之外的flightsById
,然后将其传递给setFieldValue()
。 I used the rest operator ( ...otherFlights
) to copy it without the key, but there's plenty of other methods detailed in other SO threads....otherFlights
)在没有密钥的情况下复制它,但在其他 SO 线程中详细介绍了许多其他方法。 Here is an example of deleting a single flight when a button is clicked:以下是单击按钮时删除单个航班的示例:
<button
type="button"
onClick={() => {
const { EF_700001132, ...otherFlights } = formik.values.flightsById;
formik.setFieldValue("flightsById", otherFlights);
}}
>
Delete Flight EF_700001132
</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.