简体   繁体   English

IF Else 语句在 setInterval() 函数中工作不正常

[英]IF Else statement not properly worked in setInterval() function

I have a problem with accessing if else, if else can called but both block called if block as well as else block at a same time我在访问 if else 时遇到问题,if else 可以调用,但是两个块同时调用 if 块和 else 块

so how can i make proper working if else block那么如果 else 阻塞,我如何才能正常工作

my code is我的代码是

const UserCard=(props)=>{


const[LiveOrdStatus,setStatus] = useState();
const[order_ID,setordid] = useState(props.orderId);

const labels=["Order","Confirm","Ready","Deliver","Delivred"];
let number = 0;

function LiveFetchData(){
   fetch('https://example.in/app/live_update.php', {
      method: 'POST',
      mode: 'no-cors',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        'S_KEY':'84014',
        'order_id':order_ID,
      })
    }).then((response) => response.json())
    .then((json) => {
      setStatus(json.order_status);
      //console.log(json.order_status);
    }).catch((err) => { console.log(err); });
}

LiveFetchData();
   setInterval(() => {
        if(LiveOrdStatus==="DELIVERED")
        {
         console.log("its okk :"+LiveOrdStatus);
        }else{
         console.log("not called :");
        }
  }, 10000);

 }

my output is我的输出是在此处输入图片说明

You are calling and setting an interval each render cycle and from what I can tell you never clear any intervals.您正在调用并设置每个渲染周期的间隔,据我所知,您永远不会清除任何间隔。 You likely only want to start one interval when the component mounts.您可能只想在组件安装时开始一个间隔。 Don't forget to return a cleanup function to clear any running intervals when the component unmounts.当组件卸载时,不要忘记返回一个清理函数来清除任何运行间隔。

useEffect(() => {
  const timerRef = setInterval(() => {
    if (LiveOrdStatus === "DELIVERED") {
      console.log("its okk :", LiveOrdStatus);
    } else {
      console.log("not called :");
    }
  }, 10000);

  return () => clearInterval(timerRef);
}, []);

You are also calling LiveFetchData();您还调用了LiveFetchData(); directly in the function body, which will cause render looping since it also updates state.直接在函数体中,这将导致渲染循环,因为它也会更新状态。 I'm not sure when you want this function to be called, but it's likely that you also want to place it into an useEffect hook.我不确定您希望何时调用此函数,但您很可能还希望将其放入useEffect钩子中。

useEffect(() => LiveFetchData(), []);

This will invoke it once when the component mounts, but if you need to call it more often then you should figure out what any dependencies are or add additional interval timers, etc...这将在组件安装时调用一次,但如果您需要更频繁地调用它,那么您应该弄清楚任何依赖项是什么或添加额外的间隔计时器等...

Update更新

I am facing one more problem , when accessing LiveOrdStatus inside else than it show " not called : undefined "我还面临一个问题,当访问LiveOrdStatus内部的LiveOrdStatus时,它显示“未调用:未定义”

Yeah, I see how that can happen now.是的,我现在明白这怎么可能发生。 Basically the initial LiveOrdStatus is closed over in the setInterval callback scope.基本上,初始LiveOrdStatussetInterval回调范围内关闭。

Use a React ref to cache the current LiveOrdStatus state value and access that in the interval.使用 React ref 缓存当前LiveOrdStatus状态值并在间隔内访问它。

    const LiveOrdStatusRef = React.useRef();

    useEffect(() => {
      LiveOrdStatusRef.current = LiveOrdStatus;
    }, [LiveOrdStatus]);

    useEffect(() => {
      const timerRef = setInterval(() => {
        if (LiveOrdStatus === "DELIVERED") {
          console.log("its okk :", LiveOrdStatusRef.current);
        } else {
          console.log("not called :", LiveOrdStatusRef.current);
        }
      }, 10000);

      return () => clearInterval(timerRef);
    }, []);

you should call the function which are causing side effect in useEffect hook.您应该在 useEffect 钩子中调用导致副作用的函数。

   const LiveFetchData = () => {

     fetch('https://example.in/app/live_update.php', {
     method: 'POST',
     mode: 'no-cors',
     headers: {
      'Content-Type': 'application/json',
     },
     body: JSON.stringify({
     'S_KEY':'84014',
     'order_id':order_ID,
    })
    }).then((response) => response.json())
    .then((json) => {
    setStatus(json.order_status);
    //console.log(json.order_status);
    }).catch((err) => { console.log(err); });
   }
  
   useEffect(() => {
      LiveFetchData();
    } , [])

  useEffect(() => {
    const timerRef = setInterval(() => {

    if (LiveOrdStatus==="DELIVERED") {
      console.log("its okk :"+LiveOrdStatus);
    } else {
      console.log("not called :");
    }
   }, 10000);

   return () => clearInterval(timerRef);
  }, []);

From my understanding, you're fetching LiveFetchData() , one time only when the userCard Component mounts.根据我的理解,您正在获取LiveFetchData() ,只有在userCard组件安装时才获取一次。 So you can wrap call it inside the useEffect()所以你可以在useEffect()里面调用它

useEffect(()=>{
 LiveFetchData(); // it will populate the status first
},[])

Then you can call setInterval normally to check the status.然后就可以正常调用setInterval来查看状态了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM