代码返回错误TypeError:无法读取未定义的的属性"trim">
const [category, setCategory] = useState();
const classes = useStyles();
const [fields, setFields] = useState([''
]);
const onChangeHandler = (e, i) => {
const { name , value } = e.target
const currentFields = [...fields];
currentFields[i] = value;
setFields(currentFields)
}
//Validators
const [errors, setErrors] = useState ('');
const onSubmit = (e) => {
e.preventDefault()
let errors = {};
if (!category.trim()){
errors.category="Select Type of Category is Required"
}
if (!fields.trim()){
errors.fields="Field is Required/Remove empty Fields"
}
setErrors(errors)
if (Object.keys(errors).length === 0){
formSubmit()
}
}
从我所看到的,您的category
状态初始值是未定义的。
const [category, setCategory] = useState();
您应该为它提供一个有效的字符串值。
const [category, setCategory] = useState("");
另一种选择是使用空检查
if (category && !category.trim()){
errors.category="Select Type of Category is Required"
}
或可选的链式
if (!category?.trim()){
errors.category="Select Type of Category is Required"
}
注意:在其他任何时候更新category
状态时,也应确保状态不变,即它可能始终是字符串,或者在访问该状态时应用相同的替代检查。