【问题标题】:"Hooks can only be called inside of the body of a function component" even it's inside a function component“钩子只能在函数组件的主体内部调用”,即使它在函数组件内部
【发布时间】:2020-04-06 17:02:17
【问题描述】:

我在函数组件中使用 ReactHooks useEffect。 但是,它返回错误说 Hooks 只能在函数组件的主体内部调用

我的代码是这样的

const ChildComponent = (props) => {
  useEffect(() => {
   // call for tracking event 
  }, [])
  return (
    <div>
     this is an example
    </div>
  )
}

这个exampleCode是类组件的子组件。我想这不是问题。

class ParentComponent extends React.Component {
render() {
return <exampleCode />
 }
}

react 和 react DOM 版本是 16.8.6。 我该如何解决?

【问题讨论】:

  • React 组件以大写字母开头。
  • 谢谢这是我的错字

标签: reactjs react-hooks


【解决方案1】:

一两个问题。就像其他人提到的那样,如果您提供它,您需要将组件的名称大写。你当然可以有这样的东西,它完全放弃了:

export default ({ children }) => {
  ...
};

另一件事是,你给出的例子是你有 useEffect() 但那里没有 useState(),即没有钩子让它起作用。为了清楚起见,我们是否应该假设您省略了这一点?如果您没有,我怀疑这就是您遇到此错误的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-28
    • 2021-02-08
    • 2019-11-21
    • 2020-10-27
    • 2021-10-31
    • 2021-11-11
    • 2020-02-14
    相关资源
    最近更新 更多