简体   繁体   English

如何从 Formik 中通过 Id 删除嵌套对象?

[英]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);

Console.log() results: Console.log() 结果: 在此处输入图片说明

Some feedback:一些反馈:

  • You referred to flightsById as a "nested array", but judging from your screenshot it's an object您将flightsById称为“嵌套数组”,但从您的屏幕截图来看,它是一个对象
  • You have the right idea by using setFieldValue() to update flightsById , nice work 😉通过使用setFieldValue()更新flightsById ,您的想法是正确的, flightsById好😉
  • Placing a useEffect inside an if statement will trigger an error because it breaks the rules of hooksif语句中放置 useEffect 会触发错误,因为它违反了钩子规则
  • If you want to completely remove they key 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.我使用rest 运算符...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>

Live Demo 现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM