Javascript 我想检查用户是否在React应用程序中在线? 目标

Javascript 我想检查用户是否在React应用程序中在线? 目标,javascript,reactjs,Javascript,Reactjs,我想根据用户是在线还是离线显示消息 问题摘要 错误: 太多的重新渲染。React限制渲染的数量以防止无限循环 问题主要是由setInterval()引起的,它每6秒调用一个函数来更改状态(使用useStatehook创建) 预期结果: 以设置的时间间隔调用函数,检查用户是联机还是脱机,然后在用户脱机时显示消息 我所尝试的: 导出默认函数CardContainer(){ const[isOnline,set_isOnline]=useState(true); 函数InterneterMe

我想根据用户是在线还是离线显示消息


问题摘要
  • 错误: 太多的重新渲染。React限制渲染的数量以防止无限循环
  • 问题主要是由
    setInterval()
    引起的,它每6秒调用一个函数来更改状态(使用
    useState
    hook创建)

预期结果: 以设置的时间间隔调用函数,检查用户是联机还是脱机,然后在用户脱机时显示消息


我所尝试的:
导出默认函数CardContainer(){
const[isOnline,set_isOnline]=useState(true);
函数InterneterMessager(){
如果(navigator.onLine==true)设置为isOnline(true);
如果(navigator.onLine==false)设置为isOnline(false);
}
设置间隔(InterneterMessageer(),6000);
返回(
//该组件包含脱机时显示的消息
{isOnline!==true?:“”
)

我的努力一瞥:

注意:我正在考虑使用
useffect
hook来解决此问题,但不知道如何解决。如果您正在考虑其他解决此问题的方法,请与我分享

你可以这样做

  • useffect
    将启动Useffect的setInterval on component mount返回功能,在并发卸载后删除interval事件
  • export default function CardContainer() {
     const [isOnline, set_isOnline] = useState(true);
     let interval = null;
    
     const InternetErrMessagenger = () => set_isOnline(navigator.onLine===true); // for do like this shortform
    
     
     useEffect(()=>{
        interval = setInterval(InternetErrMessagenger, 6000); // call the function name only not with function with call `()`
        return ()=>{
           clearInterval(interval) // for component unmount stop the interval
        }
     },[])
     
     return (
        // the <InternetChecker /> component contains a message that gets displayed when offline
        {isOnline !== true ? <InternetChecker /> : ""}
     )
    
    导出默认函数CardContainer(){
    const[isOnline,set_isOnline]=useState(true);
    设区间=null;
    const interneterMessager=()=>set_isOnline(navigator.onLine===true);//对于类似此缩写形式的操作
    useffect(()=>{
    interval=setInterval(InterneterMessager,6000);//仅调用函数名,而不使用带有call`()`
    return()=>{
    clearInterval(interval)//对于组件卸载,请停止间隔
    }
    },[])
    返回(
    //该组件包含脱机时显示的消息
    {isOnline!==true?:“”
    )
    
    使用
    window.addEventListener('online')
    window.addEventListener('offline')在codesandbox上解决了这个问题。

    签出

    Socket IO是开发聊天和用户在线应用程序的最佳方式。@GautamParamar OP希望检查网络状态。检查
    从“@rehooks/online status”导入UseOnline状态;
    ,然后在组件内部:
    const isOnline=UseOnline status()
    谢谢,。这是解决此问题的最简单方法。请解释一下您所做的工作。您的代码不起作用…我正在使用chrome开发工具虚拟地设置“online”和“offline”。当我将其设置为“offline”时,组件不会被渲染。@DronBhattacharya请立即尝试。setInterval函数调用错误。\now已更新。正在工作。当我在新选项卡中打开代码时,代码不工作