【发布时间】:2020-11-05 11:20:57
【问题描述】:
我发现的唯一其他答案是事件没有传递给函数。这里情况不同。我显然将事件作为变量 e 传递。我将按钮类型设置为提交,因此表单正在与事件一起提交。此外,handleChange 函数与事件一起正常工作。我从我正在学习的 Udemy 课程中复制了这种格式,我几乎拥有完全相同的东西。我能想到的唯一大区别是,Udemy 课程将所有这些逻辑都放在一个单独的组件中,该组件被导入然后呈现到页面,其中表单和表单处理逻辑是此页面上的主要组件。
请查看我的代码并告诉我我做错了什么!
代码:
import React, { useState, useEffect } from 'react'
import Router, { withRouter } from 'next/router';
import Layout from '../../components/Layout';
import { Col, Row, Button, Form, FormGroup, Label, Input } from 'reactstrap';
import { createPatient } from '../../actions/patient';
const CreatePatient = ({ router }) => {
const [ values, setValues ] = useState({
error: '',
formData: '',
data: ''
});
const { error, formData } = values;
useEffect(() => {
setValues({
...values,
formData: new FormData()
})
}, [router])
const createPatient = (e) => {
e.preventDefault();
createPatient(formData).then(data => {
if (data.error) {
setValues({ ...values, error: data.error });
}
})
}
const handleChange = name => e => {
const value = e.target.value;
formData.set(name, value);
setValues({ ...values, [name]: value, formData, error: '' });
}
return (
<Layout>
<section className="container pt-3">
<form className="form" onSubmit={ createPatient }>
<div className="row">
<div className="col-md-4 my-2">
<label htmlFor="firstName">First Name</label>
<input type="text" className="form-control" name="firstName" id="firstName" onChange={handleChange('firstName')}/>
</div>
<div className="col-md-4 my-2">
<label htmlFor="lastName">Last Name</label>
<input type="text" className="form-control" name="lastName" id="lastName" onChange={handleChange('lastName')}/>
</div>
</div>
<div className="row">
<div className="col-sm-2">
<button type="submit" className="btn btn-primary">Create</button>
</div>
</div>
</form>
</section>
</Layout>
)
}
export default withRouter(CreatePatient);
【问题讨论】:
-
你正在覆盖
createPatient。