admin管理员组

文章数量:1391934

I got error when i want to set if in customHook Code

After this i got error ->

React Hook "" is called conditionally. React Hooks must be called in the exact same order in every ponent render 

Problem is if statment when call this work good ( without if ) ->

 const =(,());

I wan't to load useDataForm ( custom hook ) if dataValid not valid and filled.

I got error when i want to set if in customHook Code

After this i got error ->

React Hook "" is called conditionally. React Hooks must be called in the exact same order in every ponent render 

Problem is if statment when call this work good ( without if ) ->

 const =(,());

I wan't to load useDataForm ( custom hook ) if dataValid not valid and filled.

Share Improve this question edited Aug 26, 2022 at 15:18 MichaelDawalalt asked Jun 30, 2022 at 20:22 MichaelDawalaltMichaelDawalalt 211 silver badge4 bronze badges 1
  • could you share more code, so that we can give a more adapted solution ? Ideally the code or the source of the custom hook, and the ponent where it is used; that'd be helpful. – Aÿlo Commented Jun 30, 2022 at 22:29
Add a ment  | 

2 Answers 2

Reset to default 3

As per React documentation, you cannot call hooks conditionally.

Here is explained in depth why.

When the need to call a hook conditionally arises, you could opt for two soutions :

  1. Either you call useDataForm and then you use contactForm only if dataValid is true
const contactForm = useDataForm(onSubmit, modelToForm(dataValid));
if (dataValid) {
    // do what you need to do with dataValid
}
// or 
return <Child data={dataValid ? contactForm : otherData} />
  1. Either you move the hook in a separate ponent and render said ponent only if dataValid is true
  2. Either, depending on the hook, you can pass the arguments conditionally. e.g. in your exemple:
const contactForm = useDataForm(onSubmit, dataValid   ? modelToForm(dataValid) : fallbackArg);

Edit:

The canary version of React introduces use, a new hook that will likely bee a standard feature in the React 19 version. This hook supersedes the rule that hooks cannot be called conditionally or within loops. You may find a way to use this hook to solve your conundrum with the custom hook. However, it's important to note that the other rules of hooks remain valid. Specifically, hooks must still be called at the top level of ponents or other hooks.

We can’t call Hooks inside of conditionals, loops, or nested functions in order to ensure that Hooks are called in the same order each time a ponent renders. The order is important for how React associates Hook calls with ponents.

Resource: https://www.benmvp./blog/conditional-react-hooks/#:~:text=We%20can%27t%20call%20Hooks,associates%20Hook%20calls%20with%20ponents.

You can check this resource maybe it can be helpful

本文标签: