【问题标题】:Error with calling React Hooks inside of Function Component在函数组件内调用 React Hooks 时出错
【发布时间】:2021-03-20 18:04:43
【问题描述】:

我不知道为什么我在运行测试后收到此错误。

Invalid hook call. Hooks can only be called inside of the body of a function component.

这就是我的代码的样子

  23 |
  24 | const LandingPageNew = () => {
> 25 |   const [displayElement, setDisplayedElement] = useState(1);
     |                                                 ^
  26 |
  27 |   const classes = useStyles();
  28 |   function manageIndicatorColors(element, number) {

您如何看到我在函数组件中使用了钩子。

您知道为什么会发生此错误吗?

我的项目中只有一个 React

$ npm ls react
   root@ C:\Users\szyma\Desktop\MVPs\pyramid_questionnaire_2
          -- client@1.0.0 -> 
   C:\Users\szyma\Desktop\MVPs\pyramid_questionnaire_2\packages\client
          -- react@17.0.1

编辑------------

这很简单。 LandingPageNew 被导入到 App.js

import LandingPageNew from "./react/LandingPageNew";

然后

function App() {
  return (
    <Router>
      <div className='appComponent'>
        {/* <img src={background} className='top-background' /> */}

        <Route path='/' exact component={LandingPageNew} />
        <Route path='/create-account' component={CreateAccountPage} />
        <Route path='/questionnaire' component={LandingPageNew} />
      </div>
    </Router>
  );
}

export default App;

App.js 中使用它后,一切都是“默认”的

【问题讨论】:

  • 你在Edit有答案
  • 能否把完整代码贴在LadingPageNew文件中
  • 给你link
  • 您似乎没有违反该组件中的挂钩规则。所以要么问题出在其他地方,要么你以某种方式混淆了 React 版本。如果您使用的是 npm link ,这可能是 stackoverflow.com/a/63705440/10648865 的原因
  • 我将clinet文件链接到更正node_modules文件夹

标签: reactjs


【解决方案1】:

我编写的每个函数组件都有必需的属性。它可能必须接受这个作为钩子识别它的参数。尝试改变

const LandingPageNew = () => {

const LandingPageNew = (props) => {

【讨论】:

    猜你喜欢
    • 2019-04-14
    • 1970-01-01
    • 2020-06-22
    • 2019-09-07
    • 2020-10-26
    • 1970-01-01
    • 2021-11-06
    • 2021-03-30
    • 1970-01-01
    相关资源
    最近更新 更多