当我创建一个实体(本例中为公司(时,我使用Formik和Yup来检查字段是否正确以及是否引入了所有字段(所有字段都是必需的(。
当我创建一个实体时,它工作得很好:只有在引入了所有字段并满足了规则的情况下,它才允许您创建它(对于电子邮件,目前只有一条规则(。
这是创建一个新公司的代码,有2个字段名称和电子邮件:
import React from 'react';
import { Redirect } from 'react-router-dom';
import { Formik, Form, Field } from 'formik';
import { Input, Button, Label, Grid } from 'semantic-ui-react';
import { connect } from 'react-redux';
import * as Yup from 'yup';
import { Creators } from '../../../actions';
import Layout from '../../Layout/Layout';
class CreateCompanyForm extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
name: '',
contactMail: '',
redirectCreate: false,
redirectEdit: false,
edit: false,
};
}
componentDidMount() {
const {
getCompany,
location: { pathname },
} = this.props;
}
handleSubmit = values => {
const { createCompany, getCompanies } = this.props;
createCompany(values);
this.setState({ redirectCreate: true });
getCompanies(this.props.query);
};
render() {
let title = 'Create Company';
let buttonName = 'Create';
let submit = this.handleSubmitCreate;
const { redirectCreate, redirectEdit } = this.state;
if (redirectCreate) {
return <Redirect to="/companies" />;
}
const initialValues = {
name: '',
contactMail: '',
};
const requiredErrorMessage = 'This field is required';
const emailErrorMessage = 'Please enter a valid email address';
const validationSchema = Yup.object({
name: Yup.string().required(requiredErrorMessage),
contactMail: Yup.string()
.email(emailErrorMessage)
.required(requiredErrorMessage),
});
return (
<Layout>
<div>
<Button type="submit" form="amazing">
Create company
</Button>
<Button onClick={() => this.props.history.goBack()}>Discard</Button>
<div>Create company</div>
</div>
<Formik
htmlFor="amazing"
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={values => this.handleSubmit(values)}>
{({ values, errors, touched, setValues }) => (
<Form id="amazing">
<Grid columns={2}>
<Grid.Column>
<Label>Company Name</Label>
<Field name="name" as={Input} placeholder="Hello" />
<div>{touched.name && errors.name ? errors.name : null}</div>
</Grid.Column>
<Grid.Column>
<Label>Contact Mail</Label>
<Field
name="contactMail"
as={Input}
placeholder="johnappleseed@hello.com"
/>
<div>
{touched.contactMail && errors.contactMail
? errors.contactMail
: null}
</div>
</Grid.Column>
</Grid>
</Form>
)}
</Formik>
</Layout>
);
}
}
const mapStateToProps = state => ({
companies: state.companies.companies,
company: state.companies.selectedCompany,
query: state.companies.query,
});
const mapDispatchToProps = {
getCompanies: Creators.getCompaniesRequest,
createCompany: Creators.createCompanyRequest,
getCompany: Creators.getCompanyRequest,
updateCompany: Creators.updateCompanyRequest,
};
export default connect(mapStateToProps, mapDispatchToProps)(CreateCompanyForm);
当我想编辑公司时,问题就出现了。因此,当有人点击某个公司的编辑按钮时,它应该打开该公司,其所有字段都包含应可编辑的当前值。
为了获得这些当前值,我正在使用状态,例如,可以从this.state.email
访问电子邮件,为了更改值,添加了onChange
方法。
可以在文本输入中修改这些值。然而,它会触发Yup消息,即即使字段中有数据,也需要该字段——为什么会发生这种情况?字段不是空的,这就是它必须显示该消息的情况。
当然,当我点击保存实体时,它不会更新它,因为它需要这些字段。
这是代码:
import React from 'react';
...
class CreateCompanyForm extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
name: '',
contactMail: '',
redirectCreate: false,
redirectEdit: false,
edit: false,
};
}
componentDidMount() {
const {
getCompany,
location: { pathname },
} = this.props;
if (pathname.substring(11) !== 'create') { // checks the URL if it is in edit mode
getCompany(pathname.substring(16));
this.setState({
edit: true,
});
this.setState({
name: this.props.company.name,
contactMail: this.props.company.contactMail,
});
}
}
onChange = (e, { name, value }) => { // method to update the state with modified value in input
this.setState({ [name]: value });
};
handleSubmit = values => {
const { createCompany, getCompanies } = this.props;
createCompany(values);
this.setState({ redirectCreate: true });
getCompanies(this.props.query);
};
handleSubmitEdit = e => {
e.preventDefault();
const { name, contactMail } = this.state;
const { updateCompany } = this.props;
updateCompany(this.props.company._id, {
name,
contactMail,
});
this.setState({ redirectEdit: true });
};
render() {
let title = 'Create Company';
let buttonName = 'Create';
let submit = this.handleSubmitCreate;
const { redirectCreate, redirectEdit } = this.state;
if (redirectCreate) {
return <Redirect to="/companies" />;
}
if (redirectEdit) {
return <Redirect to={`/companies/${this.props.company._id}`} />;
}
if (this.state.edit) {
title = 'Edit Company';
buttonName = 'Edit';
submit = this.handleSubmitEdit;
}
const initialValues = {
name: '',
contactMail: '',
};
const requiredErrorMessage = 'This field is required';
const emailErrorMessage = 'Please enter a valid email address';
const validationSchema = Yup.object({
name: Yup.string().required(requiredErrorMessage),
contactMail: Yup.string()
.email(emailErrorMessage)
.required(requiredErrorMessage),
});
return (
<Layout>
<div>
<Button type="submit" form="amazing">
Create company
</Button>
<Button onClick={() => this.props.history.goBack()}>Discard</Button>
<div>Create company</div>
</div>
<Formik
htmlFor="amazing"
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={values => this.handleSubmit(values)}>
{({ values, errors, touched, setValues }) => (
<Form id="amazing">
<Grid columns={2}>
<Grid.Column>
<Label>Company Name</Label>
<Field
name="name"
as={Input}
placeholder="Hello"
value={this.state.name || ''} // takes the value from the state
onChange={this.onChange} // does the changing
/>
<div>{touched.name && errors.name ? errors.name : null}</div>
</Grid.Column>
<Grid.Column>
<Label>Contact Mail</Label>
<Field
name="contactMail"
as={Input}
placeholder="johnappleseed@hello.com"
value={this.state.contactMail || ''} // takes the value from the state
onChange={this.contactMail} // does the changing
/>
<div>
{touched.contactMail && errors.contactMail
? errors.contactMail
: null}
</div>
</Grid.Column>
</Grid>
</Form>
)}
</Formik>
</Layout>
);
}
}
...
export default connect(mapStateToProps, mapDispatchToProps)(CreateCompanyForm);
关于如何解决这个问题,使字段可编辑,并在字段已经有数据时删除'This field is required'
消息,有什么想法吗?
您需要做3个小更改:
1.您的初始值始终设置为:
const initialValues = {
name: '',
contactMail: '',
};
您需要将其更改为:
const initialValues = {
name: this.state.name,
contactMail: this.state.contactMail,
};
2.将enableReinitialize
添加到Formik
即使更改了nº1,您的提交仍然会抛出错误,这是因为当创建组件时,Formik
会使用构造函数中的值呈现:
this.state = {
name: "",
contactMail: "",
redirectCreate: false,
redirectEdit: false,
edit: false,
};
当您更改componentDidMount
内部的状态时,Formik
不会使用更新值重新初始化:
componentDidMount() {
const {
getCompany,
location: { pathname },
} = this.props;
if (pathname.substring(11) !== 'create') { // checks the URL if it is in edit mode
getCompany(pathname.substring(16));
this.setState({
edit: true,
});
this.setState({
name: this.props.company.name,
contactMail: this.props.company.contactMail,
});
}
}
因此,要形成重新初始化,您需要向其添加enableReinitialize
,如下所示:
<Formik
htmlFor="amazing"
/// HERE'S THE CODE
enableReinitialize
initialValues={initialValues}
....
3.使用enableReinitialize
,Formik
将触发模糊和更改的验证。为了避免这种情况,您可以将validateOnChange
和validateOnBlur
添加到false:
<Formik
htmlFor="amazing"
enableReinitialize
validateOnChange={false}
validateOnBlur={false}
initialValues={initialValues}
.....