有人知道如何在表单的电子邮件字段中显示Formik setStatus消息吗?
import { Form, Checkbox, Input, Button } from 'antd';
import { withFormik } from 'formik';
import axios from 'axios';
const RegistrationForm = (props) => {
const { values, touched, errors, handleChange,
handleBlur,handleSubmit, setFieldValue, status,
} = props;
console.log(status); //undefined
return (
<Form onFinish={handleSubmit}>
<Form.Item
help={touched.email && errors.email ? errors.email : ""}
validateStatus={touched.email && errors.email ? "error" : "success"}
label="E-mail"
name="email"
>
<Input
placeholder="Email"
value={values.email}
onChange={handleChange}
onBlur={handleBlur}
/>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">Submit</Button>
</Form.Item>
</Form>
const RegFormView = withFormik({
validationSchema,
mapPropsToValues: () => ({ email: ''}),
handleSubmit: async (values, { props, setErrors, setSubmitting, setStatus }) => {
await axios.post("/signup", values)
.then((response) => {
setStatus('');
const { isAdded } = response.data;
const statusMessage = (isAdded) ? {message: 'User Added!'} : {message: 'User Not Added!'};
setStatus(statusMessage);
setSubmitting(false);
console.log('response: ', response.data);
}, (error) => { setErrors(error);
});
},
})(RegistrationForm);
export default RegFormView;
我从表格中删除了所有其他字段。 服务器响应:{i会员:false} / {i会员:true} 取决于是否有使用此电子邮件的用户
答案 0 :(得分:1)
withFormik将道具注入到您的组件中。
这些道具是Formik状态的属性以及允许您更新它的函数(例如handleChange,setFieldValue等)。
因此,您可以在withFormik包装的组件的属性中获取属性状态。
const RegForm = (props) => {
const { values, touched, status } = props;
return <YourForm>
<YourInput />
</ YourForm>
}
export default withFormik({
validationSchema,
mapPropsToValues: () => ({ name: '', password: '', email: '',}),
handleSubmit: async (values, { props, setErrors, setSubmitting, setStatus }) => {
await axios.post("/signup", values)
.then((response) => {
const { isAdded } = response.data;
const message = (isAdded) ? 'yes' : 'no';
setStatus(message);
setSubmitting(false);
}, (error) => {
setErrors(error);
});
},
})(RegForm);