我对 React 和 timout 函数有一个奇怪的问题。 出于某种原因,我希望将一个字符串逐个字母添加到
useEffect
中。所以我写了这段代码:
const [placeholder, setPlaceholder] = useState < string > ('')
useEffect(() => {
const str = "How may I help you today?";
const letters = Array.from(str);
const addLetterWithDelay = (index: number) => {
if (index < letters.length) {
setTimeout(() => {
setPlaceholder(prevPlaceholder => prevPlaceholder + letters[index]);
addLetterWithDelay(index + 1);
}, 1000); // Delay of 1 second
}
};
addLetterWithDelay(0); // Start adding letters from index 0
}, []);
问题是字母设置了两次 所以输出将是: HHooww mmaayy II hheellpp yyououu ttooddaayy?? 即使我检查一个语句占位符的最后一个字符是否与字母[索引]相同,它仍然打印出它不相同并继续执行
将你的 useEffect 修改为:
useEffect(() => {
const str = "How may I help you today?";
const letters = Array.from(str);
let timerId: NodeJS.Timeout; // Declare a variable to hold the timeout ID
const addLetterWithDelay = (index: number) => {
if (index < letters.length) {
timerId = setTimeout(() => {
setPlaceholder(prevPlaceholder => prevPlaceholder + letters[index]);
addLetterWithDelay(index + 1);
}, 1000); // Delay of 1 second
}
};
addLetterWithDelay(0); // Start adding letters from index 0
return () => clearTimeout(timerId); // Clear the timeout when the component is unmounted or the useEffect hook re-runs
}, []);
这样,如果您的组件重新渲染并再次调用 useEffect 钩子,则当前超时将被清除,并且 addLetterWithDelay 方法将被终止。