【问题标题】:Unable to call hooks in a class - react无法在类中调用钩子 - 做出反应
【发布时间】:2021-12-30 12:05:04
【问题描述】:

我正在尝试添加语音识别和他们在我的网站上所说的内容的文字记录,其中用户按下按钮启动麦克风,对着他们的麦克风说话,然后他们所说的文字记录被记录并显示在屏幕。

我在一个名为 App 的类组件中完成所有这些工作,这是我处理语音识别部分的函数:

Dictaphone = () => {
    const {
      transcript,
      listening,
      resetTranscript,
      browserSupportsSpeechRecognition
    } = useSpeechRecognition();
  
    if (!browserSupportsSpeechRecognition) {
      return <span>Browser doesn't support speech recognition.</span>;
    }
  };

在我的render() 部分,这是我返回的与我网站的语音识别部分相关的内容:

<p>Microphone: {this.Dictaphone.listening ? 'on' : 'off'}</p>
<button onClick={this.Dictaphone.SpeechRecognition.startListening}>Start</button>
<button onClick={this.Dictaphone.SpeechRecognition.stopListening}>Stop</button>
<button onClick={this.Dictaphone.resetTranscript}>Reset</button>
<p>{this.Dictaphone.transcript}</p>

我收到此错误:

Failed to compile.

src\App.js
  Line 15:9:  React Hook "useSpeechRecognition" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function  react-hooks/rules-of-hooks

我不确定为什么会出现此错误,但最重要的是,我不知道如何在不使用 useSpeechRecognition() 挂钩的情况下实际实现我想要实现的功能。我可以帮忙解决这个问题吗?

【问题讨论】:

    标签: reactjs react-hooks speech-recognition


    【解决方案1】:

    错误是简单的钩子只允许在函数组件内部。并且由于 Dictaphone 函数不是一个组件(它不返回 React 元素),它被认为是您在作为类组件的父元素内调用钩子。

    如果您希望 Dictaphone 成为一个组件,只需在末尾添加 return null

    Dictaphone = () => {
        const {
           transcript,
           listening,
           resetTranscript,
           browserSupportsSpeechRecognition
        } = useSpeechRecognition();
    
        if (!browserSupportsSpeechRecognition) {
            return <span>Browser doesn't support speech recognition.</span>;
        }
        return null;
    };
    

    并在自己的文件 Dictaphone.jsx 中创建它。

    【讨论】:

    • 我不确定您所说的“在其自己的文件 Dictaphone.jsx 中创建它”是什么意思,我是否要创建一个新文件,将 Dictaphone 组件复制并粘贴到该文件中(我需要在它前面添加一个 const 之类的东西?)并从 react 复制并粘贴语音识别模块的导入?如果我这样做正确,然后通过执行以下操作在 App.js 中导入该 jsx 文件:import './Dictaphone.jsx';。但是我如何实际使用录音机组件和里面的东西,比如“成绩单”和“听”,因为当我在我的 App.js 中渲染这些东西时,我收到了它们未定义的错误
    • 第 2 部分:这是我的 App.js 的 render() 中的示例,“Dictaphone.listening”。这就是我应该使用它的方式吗,因为每次我做“录音机。(名称)”时都会出错,这就是我得到的错误:“第 64:25 行:'录音机'未定义不-未定义"
    • 是的。简而言之,您需要创建一个功能组件才能使用钩子。您在类组件的方法中使用钩子(您同时违反了两条规则)。更多信息可以看Rules of Hooks
    猜你喜欢
    • 2019-09-25
    • 2019-08-17
    • 2020-12-02
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多