gpt4 book ai didi

reactjs - 如何使用字段数组删除formik值

转载 作者:行者123 更新时间:2023-12-04 17:33:13 25 4
gpt4 key购买 nike

我们如何在使用字段数组时删除 formik 值。所以它得到
当我删除它时从 UI 中删除,但保留在 formik 值中。
我可以直接编辑/修改 formik 值吗?
我是新来的 react 。谢谢

{
Client:
Phone: [
{
PhoneNumber:"",
PhoneType:""
}
]
}

我可以从状态中删除事件,但 formik 值仍然保留这些值。
 const Phone = ({ title, binding }) => {
const [phones, setPhones] = useState([])
return (

<Fragment>
<Grid item xs={12} md={6}>
<SectionField
title={title}
name={binding + `.Phone.PhoneNumber`}
required
label="Phone"
fullWidth
type="tel"
component={TextField}
/>
</Grid>
<Grid item xs={12} sm={3}>
<SectionField
title={title}
name={binding + `.Phone.PhoneType`}
required
defaultValue={{ label: "", value: "" }}
label="Phone Type"
suggestions={phoneTypes}
component={MuiReactSelect}
/>
</Grid>
<IconButton onClick={() => {
setPhones(currentValue => [...currentValue, {
id: generate(),
PhoneNumber: "",
PhoneType: ""
}])
}}>
<AddBoxIcon fontSize="large" />
</IconButton>
{phones.map((p, index) => (
<Fragment key={p.id}>
<Grid item xs={12} md={5}>
<SectionField
title={title}
name={binding + `.Phone[${index}].PhoneNumber`}
required
label="Phone"
fullWidth
type="tel"
component={TextField}
/>
<ErrorMessage name={`Client.Phone.${index}.PhoneNumber`} /><br />
</Grid>
<Grid item xs={12} sm={3}>
<SectionField
title={title}
name={binding + `.Phone[${index}].PhoneType`}
required
defaultValue={{ label: "", value: "" }}
label="Phone Type"
suggestions={phoneTypes}
component={MuiReactSelect}
/>
</Grid>
<IconButton onClick={() => {
setPhones(currentPhone =>
currentPhone.filter(x => x.id !== p.id))
}}>
<RemoveCircleIcon fontSize="large" />
</IconButton>
</Fragment>
))}
</Fragment>


)
};export default Phone;


Formik values:
======================================================
"Phone": {
"0": {
"PhoneNumber": "8578882942",
"PhoneType": "Home"
},
"PhoneNumber": "8578882942",
"PhoneType": "Home"
},

最佳答案

当我想从 Ui 中删除该元素但它在 formik 中的值保留在那里时,我遇到了同样的不便。
我所做的是使用 formik setFieldValue: (field: string, value: any, shouldValidate?: boolean) => void
因此,假设您正在使用按钮从 UI 中删除该元素,因此我向它的 onClick 属性添加了一个额外的内容,如下所示:

  //formik.setFieldValue({name of the element that you want to delete})
onClick = {()=>{
//whatever work you need to do for removing it from ui

//then

//formik.setFieldValue({name of the element that you want to delete})

formik.setFieldValue(index)
// here index was the name of variable that i used for that element

}}
然后在 formik 的 useFormik() 钩子(Hook)中,我做了这样的事情:
const formik = useFormik({
initialValues: {
//your initial values
},
onSubmit: (values) => {
// your onSubmit
},
setFieldValue: (field) => {
delete values.field;
},
});
对不起,我知道这个答案来晚了,但我希望它会帮助某人

关于reactjs - 如何使用字段数组删除formik值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57811758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com