【问题标题】:Invalid hooks call on top functional component无效的钩子调用顶级功能组件
【发布时间】:2020-11-08 17:08:33
【问题描述】:

我正在尝试在我的 16.14.00 react 应用程序中使用 Hooks。但是每次我使用一个,我都会收到无效的钩子警告:“https://fr.reactjs.org/warnings/invalid-hook-call-warning.html”。

我检查过:

  • 我的电话不在任何条件块中
  • “useState”调用位于函数顶部。
  • 我只有一个 react 版本。

奇怪的是我可以在其他组件中使用 Hooks,就像 React 不接受我的 App() 功能组件上的钩子一样。

这是我的代码。

import { useState } from 'react';
import Cursor from './cursor';
import CollapsiblePanel from './collapsiblePanel';
import MainPanel from './mainPanel';
import SideBar from './sidebar/sidebar';


export default function App() {
  
    const [cursorGlowing, setCursorGlowing] = useState(false);
    
    const glowCursor = (bool) => {
      setCursorGlowing(false);
    }

    return (
      <div className="app">
        <SideBar glowCursor={() => glowCursor}/>
        <Cursor glow={cursorGlowing}/>
        <CollapsiblePanel/>
        <MainPanel />
      </div>
    )
  }

如果有人已经解决了这个问题,或者我有什么误解,请纠正我:) 谢谢你的时间。

编辑: 我在我的 index.js 中使用这个应用程序:

import App from './app'
import ReactDOM from 'react-dom';
import '../public/css/MyStyle.css';
import '../public/css/nav.css';

  
  ReactDOM.render(
    App(),
    document.getElementById('root')
  );```

【问题讨论】:

  • 您在脚本的其他地方使用App 什么地方?
  • 在帖子中编辑回答:)

标签: reactjs react-hooks


【解决方案1】:

当您执行App() 时,您将其视为普通函数,而不是React 组件。当 React 看到 App 的调用时,它无法检测到它被用作功能组件 - 它只是认为它是一个正常的功能。改用 JSX 语法调用App

ReactDOM.render( <App />, document.getElementById('root') );

(你也可以使用React.createElement,但 JSX 语法更简单)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 2021-04-15
    • 2020-01-22
    • 1970-01-01
    • 2019-11-21
    • 2020-10-27
    相关资源
    最近更新 更多