[英]Call of hooks is inside of functional component give error Hooks can only be called inside of the body of a function component
I have component language for translations我有用于翻译的组件语言
const Language = (props: IOwnProps) => {
// error is in next line for useSelector
const language = useSelector(
(state: IState) => state.currentLang
);
return getTranslations(
props.languageString
);
};
in form I have validation using formik在表单中我使用 formik 进行验证
const validationSchema = () => {
const requiredFirstName = Language({
languageString: firstNameRequired,
});
return yup.object({
firstName: yup
.string()
.required(requiredFirstName)
});
};
here is form component这是表单组件
const UserForm = ({
userData: userData
setErrorIndex,
}: UserFormProps) => {
const formik = useFormik({
initialValues: {
userData: userData.firstName,
},
validationSchema,
onSubmit: (values) => {
const playerDataLocal = {
firstName: values.firstName,
};
handleSubmit(playerDataLocal);
},
});
return (
<form onSubmit={formik.handleSubmit}>
<TextField
id="firstName"
name="firstName"
label="First Name *"
defaultValue={formik.values.firstName}
onChange={formik.handleChange}
error={formik.touched.firstName && Boolean(formik.errors.firstName)}
helperText={formik.touched.firstName && formik.errors.firstName}
fullWidth
/>
</form>
);
};
export default UserForm;
in validation schema line with Language give an error: Invalid hook call.在语言验证模式行中给出错误:无效的挂钩调用。 Hooks can only be called inside of the body of a function component.
钩子只能在 function 组件的主体内部调用。
Call of Language
is from validationSchema
that is a functional component call stack of error is in line of useSelector
from Language
call of validationSchema
is inside of 'useFormik' can be this the issue? Language
调用来自validationSchema
,它是一个功能组件调用堆栈错误符合useSelector
来自validationSchema
的Language
调用在“useFormik”内部可能是这个问题吗? any ideas?有任何想法吗?
It's because validationSchema
is not a React component.这是因为
validationSchema
不是 React 组件。 You can only use hooks inside of a functional component and since validationSchema
returns something other than JSX or another component it is not classed as a React component.您只能在功能组件内部使用钩子,并且由于
validationSchema
返回的不是 JSX 或其他组件,因此它不被归类为 React 组件。
You will probably want to move your hook call up inside UserForm
and then pass the result into validationSchema
as an argument.您可能希望将您的挂钩调用移动到
UserForm
中,然后将结果作为参数传递给validationSchema
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.