【问题标题】:Where to use Usestate hook in react component在 React 组件中哪里使用 Usestate 钩子
【发布时间】:2023-01-04 22:54:22
【问题描述】:

我试图在反应中使用 UseState 钩子,但我不确定在哪里定义它。我试图在 React 组件中声明它,但编译器给出了错误

class VoiceCallComponent extends React.Component {
  const [val, setVal] = React.useState(7);
  
  ..
  ..
  ..
}

上面的代码抛出一个错误,指出标识符需要。

【问题讨论】:

    标签: reactjs twilio


    【解决方案1】:

    您不能在类组件中使用 useState。您需要一个功能组件。

    这是doc

    这是您的示例的代码:

    import React, { useState } from 'react';
    
    function VoiceCallComponent() {
      const [val, setVal] = useState(7);
    
      // rest of the component logic goes here
      return (
        // JSX
      )
    }
    

    【讨论】:

    猜你喜欢
    • 2023-03-19
    • 2021-04-04
    • 2021-11-27
    • 2020-12-05
    • 2023-03-14
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 2021-04-04
    相关资源
    最近更新 更多