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

Ahm*_*him 9 javascript reactjs react-bootstrap

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
Run Code Online (Sandbox Code Playgroud)

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

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

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

rot*_*est 21

你可以仔细阅读评论

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;
Run Code Online (Sandbox Code Playgroud)