我在React js中得到这个类型错误
我试图在react js中构建一个表单,但react抛出错误,如typeerroe的fullName未定义。有谁能帮我解决这个问题吗?提前谢谢。
×
TypeError: Cannot read property 'fullName' of undefined
Form
C:/crayond/crayondclientside/src/Form.js:45
42 | <TextField
43 | variant="outlined"
44 | label="Full Name"
> 45 | value={values.fullName}
46 | onChange ={handleInputChange}
47 | name="fullName"
48 |
View compiled
这是代码
import { makeStyles, TextField } from '@material-ui/core';
import React,{useState,useEffect} from 'react';
import Grid from '@material-ui/core/Grid';
import UseForm from './Useform';
const useStyles = makeStyles(theme =>({
root: {
'& .MuiFormControl-root': {
width:'50%',
margin:theme.spacing(1)
}
}
}))
const initialvalues = {
fullName:" ",
// password:"",
email:" ",
// profession:""
}
export default function Form() {
const classes = useStyles();
const {
values,
setValues,
handleInputChange
} = UseForm(initialvalues);
return (
<form className={classes.root}>
<Grid container>
<Grid item xs={6}>
<TextField
variant="outlined"
label="Full Name"
value={values.fullName}
onChange ={handleInputChange}
name="fullName"
/>
<TextField
variant="outlined"
label="email"
value={values.email}
onChange ={handleInputChange}
name="email"
/>
</Grid>
<Grid item xs={6}>
</Grid>
</Grid>
</form>
)
}
这是自定义钩子
import React,{useState} from 'react';
function UseForm(initialvalues) {
const [values, setValues] = useState(initialvalues);
const handleInputChange = e => {
const {name, value} = e.target
setValues({
...values,
[name]:value
})
}
return(
values,
setValues,
handleInputChange
)
}
export default UseForm
请任何人帮助我在这个问题上,我不知道反应是抛出这个错误
尝试使用?操作符来避免前端出现这种错误:
43 | variant="outlined"
44 | label="Full Name"
> 45 | value={values?.fullName}
46 | onChange ={handleInputChange}
47 | name="fullName"
另外,确保它们被初始化并从API调用中正确填充。使用any并不能解决问题,不要这样做,因为这会使你的代码出错。