我正在使用 Next.js,并尝试访问 SpeechSynthesis 浏览器的 API:
window.speechSynthesis.getVoices()
由于我使用的是 Next.js,所以我将对
window
的调用放入 useEffect
中,并且在首次加载时工作正常。
//...
const [voices, setVoices] = useState<SpeechSynthesisVoice[]>([]);
useEffect(() => {
setVoices(window.speechSynthesis.getVoices());
}, []);
//...
但是当我重新加载页面时,最奇怪的事情发生了。我在控制台中收到误导性错误,突然
window.speechSynthesis.getVoices()
没有返回任何内容。
你知道为什么吗?我应该采取什么不同的做法?
我将我的代码放入 CodeSandBox here 中的 Next.js 模板中,供您查看。
提前感谢您的帮助🙏
我尝试将函数放入 useCallback、useMemo...但没有任何效果。
简单的答案是
Run the function again
。不要使用递归。它会给你错误。
const [isLoaded, setLoaded] = React.useState(false);
// To load Voices
React.useEffect(() => {
setTimeout(() => setLoaded(true), 300);
}, []);
React.useEffect(() => {
// Don't use this condition here
// if (!isLoaded) return;
const getVoices = () => {
const availableVoices = window.speechSynthesis.getVoices();
if (voices.length) {
setState((prev) => ({ ...prev, availableVoices }));
}
};
getVoices();
}, [isLoaded]);