为React中的地图中的每个渲染元素创建一个单独的settimeout
我正在创建一个应用程序,其中有一个从对象数组创建的元素列表,并且我正在像这样的地图中渲染它们,
<div className="App">
<div className="notification-list">
{
notifications.map( (({ type, text }, i ) => {
return (
<Notification
handleClick={handleCloseNotification}
key={i}
index={i}
type={type}
text={text}
/>
)} ))
}
</div>
每个通知应该在渲染后 X 秒后消失...我已经尝试了几种方法来添加setTimeout
但到目前为止它们都没有起作用。
我
useEffect(() => {
const timer = setTimeout(() =>
notifications.map(({}, index) => (
handleCloseNotification( index )
)), 10000);
return () => clearTimeout(timer);
}, [notifications]);
也尝试过将其添加
const timer = setInterval(() => handleClick( index ), 1000);
到通知组件中。
我也尝试过这个,
<div className="notification-list">
{
notifications.map( (({ type, text }, i ) => {
const timer = setTimeout(() => {
handleCloseNotification( i)
console.log(i);
}, 10000);
return (
<Notification
handleClick={handleCloseNotification}
key={i}
index={i}
type={type}
text={text}
/>
)} ))
}
</div>
因为我有一个最初同时呈现多个通知的列表,我的期望是它们全部同时消失。然而这些元素却以10秒的间隔一一消失。
有一个表单会向表单添加新通知,这些通知应各自存在 10 秒,然后消失。这部分似乎有效,但是对于最初渲染的元素,为什么它们没有按我的预期工作?
谢谢。
I am creating an app where there is a list of elements created from an array of objects, and i am rendering them in a map like this
<div className="App">
<div className="notification-list">
{
notifications.map( (({ type, text }, i ) => {
return (
<Notification
handleClick={handleCloseNotification}
key={i}
index={i}
type={type}
text={text}
/>
)} ))
}
</div>
each notification should disappear after X seconds after being rendered... I have tried several approaches for adding the setTimeout
but none of them has worked so far.
I tried
useEffect(() => {
const timer = setTimeout(() =>
notifications.map(({}, index) => (
handleCloseNotification( index )
)), 10000);
return () => clearTimeout(timer);
}, [notifications]);
I also tried adding this
const timer = setInterval(() => handleClick( index ), 1000);
inside the Notification component.
I also tried this
<div className="notification-list">
{
notifications.map( (({ type, text }, i ) => {
const timer = setTimeout(() => {
handleCloseNotification( i)
console.log(i);
}, 10000);
return (
<Notification
handleClick={handleCloseNotification}
key={i}
index={i}
type={type}
text={text}
/>
)} ))
}
</div>
Since I have a list that initially renders several Notifications at the same time my expectation is that they all disappear at the same time. Yet the elements disappear one by one with an interval of 10 seconds between them.
There is a form that adds new notifications to the form, and those Notifications should each live for 10 seconds and then disappear. This part seems to be working but for the elements that are rendered initially why aren't they working as I expect?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论