NextJS传递的函数不是函数

ghhkc1vu  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(85)

我试图将一个函数从父函数传递给子函数,但是我得到了

TypeError: setVoiceInput is not a function

字符串
父代码:

// questionInput.js
"use client";

import styles from './questionInput.module.css';
import React, {useEffect, useState} from "react";
import Upload from "@/components/upload";
import Voice from "@/components/voice";

const QuestionInput = ({addToInputList, addToResponseList}) => {

    const [question, setQuestion] = useState("");

    const setVoiceInput = (voice) => {
        setQuestion(voice)
    }

    const handleChange = (event) => {
        setQuestion(event.target.value);
    };

    const addInput = (input) => {
        addToInputList(input);

    };

    const addResponse = (response) => {
        addToResponseList(response);
    }

    const handleSubmit = async (event) => {
        event.preventDefault();

        addInput(question)

        const fetchData = async () => {
            try {
                const url = "/api/ask-gpt";
                const response = await fetch(url, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify({question}),
                });

                if (!response.ok) {
                    throw new Error("Request failed with status: " + response.status);
                }

                const data = await response.json();
                addResponse(data)

            } catch (error) {
                console.error("Error fetching data:", error);

            }
        };

        await fetchData();

        setQuestion("");
    };

    return (
        <div className={styles.main}>

            <Upload/>
            <Voice setVoiceInput={setVoiceInput}/>

            <form id={'csv-input'} onSubmit={handleSubmit} className={styles.container}>
                <input type="text" value={question} onChange={handleChange}
                       placeholder={"Ask a question about your CSV."} className={styles.input}/>
            </form>
        </div>
    );
};

export default QuestionInput;


子函数:

// voice.js
"use client"

import 'regenerator-runtime/runtime'
import React, {useEffect, useState} from 'react';
import SpeechRecognition, { useSpeechRecognition } from 'react-speech-recognition';

const Voice = ({setVoiceInput}) => {
    console.log('test')

    const [speechRecognitionSupported, setSpeechRecognitionSupported] = useState(null)

    const {
        transcript,
        listening,
        resetTranscript,
        browserSupportsSpeechRecognition
    } = useSpeechRecognition();

    useEffect(() => {
        setSpeechRecognitionSupported(browserSupportsSpeechRecognition)
    }, [browserSupportsSpeechRecognition])

    useEffect(() => {
        setVoiceInput(transcript);
    }, [transcript, setVoiceInput, browserSupportsSpeechRecognition])

    if (speechRecognitionSupported === null) return null

    if (!speechRecognitionSupported) {
        return <span>Browser does not support speech recognition.</span>
    }


    return (
        <div>
            <p>Microphone: {listening ? 'on' : 'off'}</p>
            <button onClick={SpeechRecognition.startListening}>Start</button>
            <button onClick={SpeechRecognition.stopListening}>Stop</button>
            <button onClick={resetTranscript}>Reset</button>
        </div>
    );
};
export default Voice;


我已经确保没有 prop 错误,并且名称相同。
我在voice上尝试了console.log(setVoiceInput),发现voice组件运行了多次。第一次它有函数,但其他时候它是未定义的。下面是一个示例:

(function here)
undefined
undefined
(function here)


编辑:我找到解决方案了!我不小心在别处调用了该组件。

tv6aics1

tv6aics11#

尝试在useEffect中更改依赖关系数组可能有效!!

相关问题