类型错误:无法读取未定义的属性“fullName”

时间:2021-01-19 15:20:15

标签: javascript reactjs react-native react-redux react-forms

我在 React js 中遇到这种类型的错误

我试图在 react js 中构建一个表单,但是 react 抛出了错误,就像 typeerroe the fullName in undefined 一样。任何人都可以帮助我解决这个问题。提前谢谢。

×
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

请任何人帮助我解决这个问题我不知道你的反应是抛出这个错误

1 个答案:

答案 0 :(得分:0)

尝试使用?操作员避免前端出现此类错误:

  43 |     variant="outlined"
  44 |     label="Full Name"
> 45 |     value={values?.fullName}
  46 |     onChange ={handleInputChange}
  47 |     name="fullName"

此外,请确保它们已通过 API 调用进行初始化和正确填充。 使用 any 并不能解决问题,不要这样做,因为这会使您的代码出错。