React Formik:如何将 Effect 与 formik 值一起使用?
React Formik : How to useEffect with formik values?
如果 formik 的值发生变化,我想使用 useEffect 重新呈现一个字段。但是没用..
实际上我创建了一个小例子来说明我的问题。
这里我有一个字段 'title',如果这个字段发生了变化(当我们在其中写入时),它应该调用 useEffect 并打印 'update!' 但它没有!
const FormikWidgetConfigurator = (props) => {
useEffect(() => {
// doesn't work if values has changed
console.log('update!')
}, [props.values]);
return (
<Form onSubmit={ props.handleSubmit } noValidate>
<Form.Group className='py-3' >
<Col md='6' style={{ padding: '0px' }}>
<Form.Group controlId='title'>
<Form.Control
type='text'
value={ props.values.title }
onChange={props.handleChange}
/>
</Form.Group>
</Col>
</Form.Group>
</Form>
)
}
const WidgetConfigurator = withFormik({
mapPropsToValues(props) {
return {
title: 'No Title'
};
},
validationSchema: props => Yup.object().shape({title: Yup.string()}),
handleSubmit(values, { setSubmitting }) {// handle submit}
})(FormikWidgetConfigurator);
export default WidgetConfigurator;
编辑:实际上它按预期工作。 (我没有改变任何东西)
谢谢!
使用 vanilla Formik
你的方法有效。
我猜问题出在您的自定义组件 Form.Control
或 Form.Group
这不是一个很好的解决方案,但我发现的一个技巧是在 Formik 表单中有一个不可见的按钮;它可以访问 Formik 的所有属性,并将执行其 onClick
中需要的任何逻辑。然后从 useEffect
你可以通过 document.getElementById("..").click()
.
模拟点击那个按钮
// Style it to be invisible
<Button id="testButton" type="button" onClick={() => {
setFieldValue('test', '123');
setTouched({});
// etc. any Formik action
}}>
</Button>
使用效果:
useEffect(() => {
document.getElementById("testButton").click(); // Simulate click
}, [dependency);
如果 formik 的值发生变化,我想使用 useEffect 重新呈现一个字段。但是没用..
实际上我创建了一个小例子来说明我的问题。 这里我有一个字段 'title',如果这个字段发生了变化(当我们在其中写入时),它应该调用 useEffect 并打印 'update!' 但它没有!
const FormikWidgetConfigurator = (props) => {
useEffect(() => {
// doesn't work if values has changed
console.log('update!')
}, [props.values]);
return (
<Form onSubmit={ props.handleSubmit } noValidate>
<Form.Group className='py-3' >
<Col md='6' style={{ padding: '0px' }}>
<Form.Group controlId='title'>
<Form.Control
type='text'
value={ props.values.title }
onChange={props.handleChange}
/>
</Form.Group>
</Col>
</Form.Group>
</Form>
)
}
const WidgetConfigurator = withFormik({
mapPropsToValues(props) {
return {
title: 'No Title'
};
},
validationSchema: props => Yup.object().shape({title: Yup.string()}),
handleSubmit(values, { setSubmitting }) {// handle submit}
})(FormikWidgetConfigurator);
export default WidgetConfigurator;
编辑:实际上它按预期工作。 (我没有改变任何东西)
谢谢!
使用 vanilla Formik
你的方法有效。
我猜问题出在您的自定义组件 Form.Control
或 Form.Group
这不是一个很好的解决方案,但我发现的一个技巧是在 Formik 表单中有一个不可见的按钮;它可以访问 Formik 的所有属性,并将执行其 onClick
中需要的任何逻辑。然后从 useEffect
你可以通过 document.getElementById("..").click()
.
// Style it to be invisible
<Button id="testButton" type="button" onClick={() => {
setFieldValue('test', '123');
setTouched({});
// etc. any Formik action
}}>
</Button>
使用效果:
useEffect(() => {
document.getElementById("testButton").click(); // Simulate click
}, [dependency);