如何在 React JS 中 5 秒后消失警报?

新手上路,请多包涵
import { useState } from 'react'

    const Message = ({ variant, children }) => {
      const [timeOut, setTimeOut] = useState(null)

      setTimeout(() => {
        setTimeOut(1)
      }, 3000)

      return (
        timeOut !== 1 && <div className={`alert alert-${variant}`}>{children}</div>
      )
    }

    Message.defaultPros = {
      variant: 'info',
    }

    export default Message

我想在 2 或 3 秒后消失此警报。我使用了这个逻辑,它很好并且可以工作,但是在我的控制台中,我收到了这个警告:

警告:无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要修复,请在 useEffect 清理函数中取消所有订阅和异步任务。

它会影响我的应用程序还是可以?你可以给我一个更好的想法来实现这个逻辑。

原文由 Ahmed Ibrahim 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 500
2 个回答

您可以阅读评论

import { useState, useEffect } from 'react'

const Message = ({ variant, children }) => {
  const [show, setShow] = useState(true)

  // On componentDidMount set the timer
  useEffect(() => {
    const timeId = setTimeout(() => {
      // After 3 seconds set the show value to false
      setShow(false)
    }, 3000)

    return () => {
      clearTimeout(timeId)
    }
  }, []);

  // If show is false the component will return null and stop here
  if (!show) {
    return null;
  }

  // If show is true this will be returned
  return (
    <div className={`alert alert-${variant}`}>
      {children}
    </div>
  )
}

Message.defaultPros = {
  variant: 'info',
}

export default Message;

原文由 rotimi-best 发布,翻译遵循 CC BY-SA 4.0 许可协议

这将在 3 秒内显示警报,然后它会消失:

 import React, { useEffect, useState } from 'react';

const Message = ({ variant, children }) => {
  // the alert is displayed by default
  const [alert, setAlert] = useState(true);

  useEffect(() => {
    // when the component is mounted, the alert is displayed for 3 seconds
    setTimeout(() => {
      setAlert(false);
    }, 3000);
  }, []);

  return (
    {alert && <div className={`alert alert-${variant}`}>{children}</div>}
  )
}

原文由 VersifiXion 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题