我的目标:
我正在尝试构建一个组件,当你给它props.items
和 props.fadeEvery
,它将充当文本旋转器。我最终希望它淡入淡出,但我的 window.setInterval
有问题.
可能的问题:
我调用 setIndex
在 useEffect
钩子(Hook),但这不是一个好习惯吗?我如何让它无限地遍历数组项?
TextFade.tsx
// Imports: Dependencies
import React, { useState, useEffect } from 'react';
// TypeScript Type: Props
interface Props {
items: Array<string>,
fadeEvery: number,
};
// Component: Text Fade
const TextFade: React.FC<Props> = (props): JSX.Element => {
// React Hooks: State
const [ index, setIndex ] = useState<number>(0);
// React Hooks: Lifecycle Methods
useEffect(() => {
const timeoutID: number = window.setInterval(() => {
// End Of Array
if (index > props.items.length) {
// Set Data
setIndex(0);
}
else {
// Set Data
setIndex(index + 1);
}
}, props.fadeEvery * 1000);
// Clear Timeout On Component Unmount
return () => window.clearTimeout(timeoutID);
}, []);
return (
<div id="text-fade-container">
<p id="text-fade-text">{props.items[index]}</p>
</div>
);
};
// Exports
export default TextFade;
最佳答案
您的索引值取自初始关闭,除非再次调用 useEffect 回调,否则它不会更新。您可以改为使用功能方式来更新状态
useEffect(() => {
const timeoutID: number = window.setInterval(() => {
// End Of Array
setIndex(prevIdx => {
if (prevIdx > props.items.length) {
// Set Data
return 0;
}
else {
// Set Data
return prevIdx + 1;
}
})
}, props.fadeEvery * 1000);
// Clear Timeout On Component Unmount
return () => window.clearTimeout(timeoutID);
}, []);
关于javascript - react : setInterval Not working after one interval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66993916/