![](/img/trans.png)
[英]Getting this error “Invalid hook call. Hooks can only be called inside of the body of a function component.” inside a react functional component?
[英]Call of hooks is inside of functional component give error Hooks can only be called inside of the body of a function component
我有用於翻譯的組件語言
const Language = (props: IOwnProps) => {
// error is in next line for useSelector
const language = useSelector(
(state: IState) => state.currentLang
);
return getTranslations(
props.languageString
);
};
在表單中我使用 formik 進行驗證
const validationSchema = () => {
const requiredFirstName = Language({
languageString: firstNameRequired,
});
return yup.object({
firstName: yup
.string()
.required(requiredFirstName)
});
};
這是表單組件
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;
在語言驗證模式行中給出錯誤:無效的掛鈎調用。 鈎子只能在 function 組件的主體內部調用。
Language
調用來自validationSchema
,它是一個功能組件調用堆棧錯誤符合useSelector
來自validationSchema
的Language
調用在“useFormik”內部可能是這個問題嗎? 有任何想法嗎?
這是因為validationSchema
不是 React 組件。 您只能在功能組件內部使用鈎子,並且由於validationSchema
返回的不是 JSX 或其他組件,因此它不被歸類為 React 組件。
您可能希望將您的掛鈎調用移動到UserForm
中,然后將結果作為參數傳遞給validationSchema
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.