【问题标题】:Use hook in class component React在类组件 React 中使用钩子
【发布时间】:2020-12-11 14:19:56
【问题描述】:

您好,我已经检查了有关该主题的几篇文章,但没有成功。 如果可能的话,我想举个例子。

import React from 'react'
import { useInView } from 'react-intersection-observer'
 
const Component = () => {
  const [ref, inView, entry] = useInView({
    /* Optional options */
    threshold: 0,
  })
 
  return (
    <div ref={ref}>
      <h2>{`Header inside viewport ${inView}.`}</h2>
    </div>
  )
}

没关系

class Nameclasse extends Component
{
   constructor(props)
    {
      super(props);
     
      const [ref, inView, entry] = useInView({
        /* Optional options */
        threshold: 0,
      })
    }
     render()
    { 
      
      return (<div></div>);
    }

}

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

  1. 您的 React 和渲染器版本可能不匹配(例如 React DOM)
  2. 您可能违反了 Hooks 规则
  3. 您可能在同一个应用程序中拥有多个 React 副本 有关如何调试和修复此问题的提示,请参阅 fb.me/react-invalid-hook-call。

【问题讨论】:

  • 你不能在基于类的反应中使用钩子。它只是根据规格的方式。 reactjs.org/docs/…

标签: javascript reactjs react-hooks


【解决方案1】:

使用 Hook 进行状态管理是函数式开发独有的,对于类中状态的任何更改,都必须通过继承的函数 this.setState();

功能前:

function Counter() {
    const [count,setCount] = useInView(0)
    return (<div> <button onclick={() => {setCount(count + 1)}}>Click me + 1</button> {count}</div>);
}

【讨论】:

    【解决方案2】:

    在我看来,React Hook 是在您不喜欢使用 (react) 组件的情况下使用状态的一个选项。因此语法应该是这样的:

    class Example extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          const [ref, inView, entry]: useInView({
             /* Optional options */
             threshold: 0,
          })
        };
      }
    
      render() {
        return (
          <>
          </>
        );
      }
    }
    

    如果这行得通(没时间),我不知道,但也许值得一试,或者其他一些更有经验的编码人员可以帮助你:)

    来源:https://reactjs.org/docs/hooks-state.html

    【讨论】:

      猜你喜欢
      • 2019-12-12
      • 2020-12-21
      • 2020-12-22
      • 2023-01-04
      • 1970-01-01
      • 1970-01-01
      • 2019-04-21
      相关资源
      最近更新 更多