【发布时间】:2021-04-09 14:02:54
【问题描述】:
我已经开发了反应应用程序,路由器有 2 条路由。在一个页面中,我正在显示值,在另一个页面中,我有一个表单,它有两个输入字段(电子邮件和电话)和一个按钮。我有每个输入字段的 Onchange 事件。一旦我在输入字段中进行更改并且没有单击更新按钮,如果我返回第一页,数据就会更新而不提交。但是刷新后它会恢复到原始值。 你能帮我吗,如何避免更新数据。 提前致谢。
这是我的代码:
import NumberFormat from 'react-number-format'
import {
useForm,
Controller,
ErrorMessage,
} from 'react-hook-form/dist/react-hook-form.ie11'
import isValidEmailAddress from '../utility/isValidEmailAddress'
import Messages from './Messages'
import Button from './Button'
import { useLocation } from 'react-router-dom'
export default function EditContactInformation({
changeContactInfoSmall,
contactInfo,
updateContactInfo,
}) {
const { handleSubmit, register, control, errors } = useForm()
return (
<form onSubmit={handleSubmit(() => changeContactInfo(contactInfo))}>
<h3>Edit contact information</h3>
<Messages results={contactInfo} />
<div className="edit-contact-information__form-col">
<div className="form-group form-group--email">
<label htmlFor="email">Preferred email address</label>
<input
name="email"
id="email"
type="text"
ref={register({
required: 'Please enter an email address',
validate: (value) =>
isValidEmailAddress(value) ||
'Please enter a valid email address',
})}
onChange={(e) => {
updateContactInfo('email', e.currentTarget.value)
return e.currentTarget.value
}}
defaultValue={contactInfo.get('email')}
/>
<ErrorMessage
errors={errors}
name="email"
as={<div className="form-errors" />}
/>
</div>
<div className="form-group form-group--phone">
<label htmlFor="phone">Preferred phone</label>
<Controller
as={<NumberFormat id="phone" format="(###) ###-####" mask="_" />}
name="phone"
rules={{
required: 'Please enter a phone number',
minLength: {
value: 10,
message: 'Please enter a valid phone number',
},
}}
onChangeName="onValueChange"
onChange={([{ value }]) => {
updateContactInfo('phone', value)
return value
}}
control={control}
defaultValue={contactInfo.get('phone')}
/>
<ErrorMessage
errors={errors}
name="phone"
as={<div className="form-errors" />}
/>
</div>
</div>
<div className="form-group">
<label>
<input
type="checkbox"
name="updateAll"
data-testid="update-all-button"
onChange={(e) => {
updateContactInfo('updateAll', e.currentTarget.checked)
}}
ref={register()}
/>{' '}
Update my contact information for all properties
</label>
</div>
<Button
className="button--primary"
arrow
type="submit"
isLoading={contactInfo.get('submitting')}
>
Update contact
</Button>
</form>
)
}
EditContactInformation.propTypes = {
changeContactInfo: PropTypes.func.isRequired,
contactInfo: PropTypes.object.isRequired,
updateContactInfo: PropTypes.func.isRequired,
}
【问题讨论】:
标签: reactjs