2 回答
TA贡献1848条经验 获得超6个赞
如果某些项目不可见,您可以设置超时并触发更新。
并跟踪是否显示新项目revealed,如果没有显示新项目,则停止流程。
function TodoApp() {
const [items, setItems] = React.useState([
{ id: 1, isDisplayed: false },
{ id: 2, isDisplayed: false },
{ id: 3, isDisplayed: false },
]);
React.useEffect(() => {
let currentTimeout = null;
const displayMoreItems = () => {
setItems(prevItems => {
let revealed = false;
const nextItems = prevItems.map(item => {
if (!revealed && !item.isDisplayed) {
revealed = true;
return { ...item, isDisplayed: true };
}
return item;
});
if (revealed) {
currentTimeout = setTimeout(() => {
displayMoreItems();
}, 1000);
}
return nextItems;
});
};
currentTimeout = setTimeout(() => {
displayMoreItems();
}, 1000);
return () => {
if (currentTimeout) {
clearTimeout(currentTimeout);
}
};
}, [setItems]);
return <div>{items.map(item => (item.isDisplayed ? item.id : null))}</div>;
}
ReactDOM.render(<TodoApp />, document.querySelector('#app'));
这是一个小提琴
TA贡献2051条经验 获得超10个赞
const DELAY = 2000;
React.useEffect(() => {
let count = 1;
array.forEach((item) => {
if (!item.displayed) {
setTimeout(() => {
item.displayed = true;
setArray([...array]);
}, DELAY * count);
count ++;
}
})
}, [])
添加回答
举报