Invalid hook call ERROR if I try to use hooks in component

huangapple go评论76阅读模式
英文:

Invalid hook call ERROR if I try to use hooks in component

问题

我有一个功能组件,其中包括

```javascript
import facebookLogin from '../functions/facebookLogin';

function NetworksList(props) {

    const getUserInfo = () => {
        console.log('beforeError')
        console.log(facebookLogin())
    }

    return (
        <View style={styles.NetworksList}>
            <TouchableOpacity onPress={getUserInfo}>
                <Text style={styles.whiteTitle}>PushToFB</Text>
            </TouchableOpacity>
        </View>
    )
}

和接下来的

function facebookLogin() {

  const [user, setUser] = useState(0)

  return (
    <>
        你好世界
    </>
  )
}

export default facebookLogin;

当我点击"PushToFB"文本后,我看到一个错误:

Error: 无效的钩子调用。钩子只能在函数组件的主体内调用。这可能是以下原因之一:

  1. 您可能在React和渲染器(如React DOM)的版本不匹配时发生了版本不匹配。
  2. 您可能正在违反Hooks的规则。
  3. 您的应用程序中可能有多个React的副本。
    请参阅https://reactjs.org/link/invalid-hook-call以获取有关如何调试和修复此问题的提示。js引擎:hermes

我已经检查了React的版本,希望正确阅读了Hooks的规则,重新安装了npm。


<details>
<summary>英文:</summary>

I have one functional component with


import facebookLogin from '../functions/facebookLogin';

function NetworksList(props) {

const getUserInfo = () =&gt; {
    console.log(&#39;beforeError&#39;)
    console.log(facebookLogin())
}

return (
    &lt;View style={styles.NetworksList}&gt;
        &lt;TouchableOpacity onPress={getUserInfo}&gt;
            &lt;Text style={styles.whiteTitle}&gt;PushToFB&lt;/Text&gt;
        &lt;/TouchableOpacity&gt;
    &lt;/View&gt;
)

}


and the next one 


function facebookLogin() {

const [user, setUser] = useState(0)

return (
<>
Hello, world
</>
)
}

export default facebookLogin;


and after I push to &quot;PushToFB&quot; text I see an error:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem., js engine: hermes

I checked versions of React, hope, wright read rules of hooks, reinstalled npm. 


</details>


# 答案1
**得分**: 2

你遇到的错误意味着你正在尝试以不允许的方式使用钩子(hook)或组件,这基于“钩子规则”。

在这种情况下,有一些问题:

* 你试图调用一个React组件,就好像它是一个常规函数一样。所以,执行`facebookLogin()`是行不通的。

* 你实际上是在另一个函数内部调用了`facebookLogin()`。由于`getUserInfo()`既不是React组件也不是钩子,你违反了上述规则 - “钩子只能在函数组件的主体内部调用”。

---

如果我理解正确,你正在尝试在按钮点击事件上动态显示`facebookLogin`组件,通常你会想要使用状态来实现。

**例如:**

```ts
import facebookLogin from 'functions/facebookLogin';

function NetworksList(props) {
    const [isVisible, setIsVisible] = useState(false);

    return (
        <View style={styles.NetworksList}>
            <TouchableOpacity onPress={() => setIsVisible(true)}>
                <Text style={styles.whiteTitle}>PushToFB</Text>
            </TouchableOpacity>

            {/* 仅在`isVisible`的值为`true`时渲染组件 */}
            {isVisible && <facebookLogin />}
        </View>
    )
}

你也可以使用按钮来在打开和关闭状态之间切换,而不仅仅是打开,如果你像这样编写:

<TouchableOpacity onPress={() => setIsVisible(prev => !prev)}>

附言 - 使用标题大小写来命名React组件。所以,不要使用facebookLogin,而应该使用FacebookLogin

英文:

The error you are getting means that you are trying to use a hook or a component in a way that is not allowed based on the "rules of hooks".

In this case there are a few problems:

  • You are trying to call a React component as if it was a regular functions.
    So doing facebookLogin() is not something that would work.

  • You are actually calling facebookLogin() within another function.
    And since getUserInfo() is not a React component nor a hook, you are breaking the mentioned rule - Hooks can only be called inside of the body of a function component.


If I understand correctly and what you are trying to do is dynamically show the facebookLogin component upon the button click event, you'd usually want to use a state for that.

For example:

import facebookLogin from &#39;../functions/facebookLogin&#39;;

function NetworksList(props) {
    const [isVisible, setIsVisible] = useState(false);

    return (
        &lt;View style={styles.NetworksList}&gt;
            &lt;TouchableOpacity onPress={() =&gt; setIsVisible(true)}&gt;
                &lt;Text style={styles.whiteTitle}&gt;PushToFB&lt;/Text&gt;
            &lt;/TouchableOpacity&gt;

            { /* Only render the component if the value of `isVisible` is `true` */ }
            {isVisible &amp;&amp; &lt;facebookLogin /&gt;}
        &lt;/View&gt;
    )
}

You could also use the button to toggle between open and closed states, instead of only opening, if you write something like this:

&lt;TouchableOpacity onPress={() =&gt; setIsVisible(prev =&gt; !prev)}&gt;

P.S. - Use title case for React component names.
So instead of facebookLogin, it should be FacebookLogin.

huangapple
  • 本文由 发表于 2023年6月22日 02:15:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76526090.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定