问题描述
当我创建实体(在这种情况下为公司)时,我使用Formik和Yup来检查字段是否正确以及是否全部引入(全部为必填项)。
当我创建一个实体时,它可以很好地工作:只有在所有字段都被引入并且满足规则的情况下,您才可以创建它(电子邮件中目前只有一个规则)。
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: '',};
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: '',};
}
componentDidMount() {
const {
getCompany,} = 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: '',};
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,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,});
}
}
因此,要重新初始化Formik,您需要向其添加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}
.....