简体   繁体   English

无效的钩子调用 - useContext - React Hooks

[英]Invalid hook call - useContext - React Hooks

I am getting an error invalid hooks call when I am using useContext in function.当我在 function 中使用 useContext 时,我收到错误的无效挂钩调用。 Please find below code.请找到下面的代码。 and suggest solution.并提出解决方案。

import React from 'react';
import { AddlistContext } from '@contexts';

const asyncCall = (value) => {
  const context = React.useContext(AddlistContext);
  console.log(value, context);
  return '';
};

Here is the code Using context in validation.js这是在validation.js中使用上下文的代码

Please I need help desperately.请我迫切需要帮助。

Thanks in Advance提前致谢

Your ValueRequired is not a component, or at least you're not using it as a component.您的 ValueRequired 不是组件,或者至少您没有将其用作组件。 At the moment, you are calling it as a plain function.目前,您将其称为普通的 function。

I know that there is a lot of confusion between a function and a react functional component as the latter seems to be simply a function.我知道 function 和反应功能组件之间存在很多混淆,因为后者似乎只是 function。 To create a component, the first thing you need is a named function, an anonymous function cannot be a component, with a capital first letter ( doc ).要创建组件,首先需要的是一个名为 function,匿名 function 不能是一个组件,首字母大写( doc )。 But most importantly, you need to call it in a way that make React render it, otherwise there is no way you can us React functionality like hooks or context.但最重要的是,您需要以一种让 React 渲染它的方式调用它,否则您无法使用 React 功能,如钩子或上下文。

For ValueRequired to not throw an error, you need to call it like this:要使 ValueRequired 不引发错误,您需要像这样调用它:

// Somewhere in you're render function
<ValueRequired />

But that won't solve your problem.但这不会解决你的问题。 In your case, I think you should use the hook pattern as they can access the context:在您的情况下,我认为您应该使用钩子模式,因为它们可以访问上下文:

  1. Create a useValueRequired function创建一个使用ValueRequired function
  2. Call it in your app or the component that manage your form在您的应用程序或管理表单的组件中调用它

Try something like this:尝试这样的事情:

const useValueRequired = () => {
    const context = React.useContext(AddlistContext);

    isRequired = value => {
        if (!value) {
            return "value is required";
        }
    }
    
    return {
        isRequired,
    };
}

const App = () => {
    // ...
    const { isRequired } = useValueRequired();
   
    // ...
    <Controller
        render={(props) => {
            return (
                <TextField
                    variant="outlined"
                    label="name"
                    fullWidth
                    {...props}
                    error={errors?.name}
                    helperText={errors?.name?.message}
                />
            );
        }}
        control={control}
        name="name"
        rules={{ validate: isRequired }}
    />

   // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM