[英]Error Hydration failed with react-speech-recognition
我想在 NextJS 13 中嘗試語音識別。我安裝了react-speech-recognition並復制/粘貼了提供的示例。 但我收到Error: Hydration failed because the initial UI does not match what was rendered on the server.
我試圖回滾對v18.1
做出反應,刪除了.next
文件夾,但它沒有幫助。 我滾動了有關React Hydration Error的 NextJS 文檔,但我沒有調用windows
也沒有將div
標簽放在p
中。
任何想法可能是什么問題?
代碼:
'use client'
import 'regenerator-runtime/runtime'
import React from 'react'
import SpeechRecognition, {
useSpeechRecognition,
} from 'react-speech-recognition'
export default function page() {
const {
transcript,
listening,
resetTranscript,
browserSupportsSpeechRecognition,
} = useSpeechRecognition()
if (!browserSupportsSpeechRecognition) {
return <span>Browser doesn't 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>
<p>{transcript}</p>
</div>
)
}
水合作用錯誤是由這些行引起的:
if (!browserSupportsSpeechRecognition) {
return <span>Browser doesn't support speech recognition.</span>
}
因為您使用的是'use client'
指令,所以該組件的行為與以前 Next.js 版本上的傳統頁面組件相同(該頁面被預渲染,然后發送到客戶端進行水合)。 您正在使用的庫檢查window
對象中是否存在webkitSpeechRecognition
或SpeechRecognition
以便設置browserSupportsSpeechRecognition
布爾值,但window
在服務器端不可用(它是undefined
)。 上面的條件計算為true
,因此在服務器上呈現的內容和客戶端的第一次呈現之間造成不匹配(您可以查看頁面的源代碼,您會注意到在服務器上呈現了不受支持的文本)。
您可以使用useState
和useEffect
掛鈎解決問題,利用useEffect
僅在客戶端運行的事實:
'use client'
import React, { useState, useEffect } from 'react'
import 'regenerator-runtime/runtime'
import SpeechRecognition, {
useSpeechRecognition
} from 'react-speech-recognition'
const Page = () => {
const [speechRecognitionSupported, setSpeechRecognitionSupported] =
useState(null) // null or boolean
const {
transcript,
listening,
resetTranscript,
browserSupportsSpeechRecognition
} = useSpeechRecognition()
useEffect(() => {
// sets to true or false after component has been mounted
setSpeechRecognitionSupported(browserSupportsSpeechRecognition)
}, [browserSupportsSpeechRecognition])
if (speechRecognitionSupported === null) return null // return null on first render, can be a loading indicator
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>
<p>{transcript}</p>
</div>
)
}
export default Page
我遇到了同樣的問題,但我認為檢查服務器渲染(當 window object 未定義時)是一個不那么混亂的解決方案:
const isServer = typeof window === "undefined";
if (!browserSupportsSpeechRecognition && !isServer) {
return <div>Your browser does not support speech recognition.</div>;
}
效果很好!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.