我是新来反应并使用钩子的人
我要实现的是单击提交按钮后,获取必要的期望值,然后通过将状态设置为新对象,将所有字段重置为空白。
我能够获得必要的值,并且我希望将状态值设置为新的默认对象会重置文本字段的值,但是看来我失败了。
有人会告诉我为什么会发生这种行为吗?
顺便说一句:使用Material-ui文本字段
可以在https://github.com/blackmo18/react-usestate-error.git
进行设置这是我的组件结构:
<Register/>
|
| --> <StudentDetails/>
| |
| |
| | --> <PersonDetails/>
| |
| - - - x --> <GuardianDetails/>
| |
| | --> <PersonDetails/>
| | --> <PersonDetails/>
|
| --> <ButtonSubmit/>
每个组件的伪代码:
数据类
Person {
firstName
lastName
middleName
.....
}
Guardian {
father : Person
mother: Person
}
BaseStudent {
id: number
person: Person
}
Student: BaseStudent {
guardian: Guardian
}
注册组件
const [studentDetails, setStudentDetails] = useState(new Student())
const [baseStudent, setBaseStudent] = useState(new BaseStudnet())
const [guardian, setGuardian] = useState(new Guardian())
const handleSubmit= (student: BaseStudent) => {
setBaseStudent(student)
setStudentDetails(Object.assign(studentDetails, baseStudent))
// -- call api
....
setBaseStudent(new BaseStudent())
setGuardian(new Guardian())
}
const handleGuardian = (guardian) => {
setGuardian(guardian)
setStudentDetails(Object.assign(studentDetails, guardian)}
}
return (
<StudentDetails
onSubmit = {handleSubmit}
>
<GuardianDetails
onChange = {handleGuardian}
/>
</StudentDetails>
)
PersonDetails组件
const {person, onChange} = props
const [person, setPerson] = useState(person? person : new Person())
const handleFirstName = (e) => {
setPerson(Object.assign(person, {firstName: event.target.value}))
handleChange()
}
.................
const handleChange = () => {
if (onChange) {
onChange(person)
}
}
return (
<div>
<TextField
label = 'firstName'
deafultValue = {person.firstName || ''}
onChange = {e => {handleFirstName(e)}}
/>
........
</div>
)
学生组成部分
const {onSubmit, value} = props
const [student, setStudent] = usetState(value ? value : new BaseStudent())
const getPerson = (person) => {
setStudent(Object.assign(student, {person: person})
}
const handleChangeId = (e) => {
setStudent(Object.assign(student, {id : e.event.target.value})
}
const handleSubmit = () => {
if (onSubmit) {
onSubmit(studentDetails)
}
}
return (
<TextField
label = 'id'
onChange = {e => {handleId(e)}}
/>
<Person
person = {student.person}
onChange = {getPerson}
/>
<Button onClick = {handleSubmit}>Submit</Button>
)
监护组件
const {value, onChange} = props
const [guardian, setGuardian] = useState(value ? value : new Guardian());
const [mother, setMother] = useState(new PersonState(new Person()));
const [father, setFather] = useState(new PersonState(new Person()));
const handleMother = (personMother) {
setMother(personMother)
setGuardian(Object.assign(guardian {mother: mother})
handleChange({mother: mother})
}
....
const hanldeChange = (parent) => {
setGuardian(Object.assign(guardian, parent))
if (onChange) {
onChange(guardian)
}
}
return (
<div>
<PersonDetails
person = {mother}
onChange = {handleMother}
/>
<PersonDetails
...........
/>
</div>
)