【问题标题】:Currently, it continues to run after 1min. I want it stop if the condition is met目前,它会在 1 分钟后继续运行。如果满足条件,我希望它停止
【发布时间】:2023-01-21 21:06:05
【问题描述】:

下面,如果 processingStatus[0] === "DELIVERED",我想清除间隔。

useEffect(() => {
    dispatch(fetchDeliveryStatus({ client_id: user.id }));

    // Fetching data changes after 1 Minute
    const interval = setInterval(() => {
      dispatch(fetchDeliveryStatus({ client_id: user.id }));
      // nextStep();
    }, 60000);

    if (processingStatus[0] === "DELIVERED") {
      return () => clearInterval(interval);
    }
  }, [dispatch]);

【问题讨论】:

    标签: react-native


    【解决方案1】:

    你可以像这样使用useRef()

    const YourComponent = () => {
        const processingStatus = useSelector(...);
        const processingStatusRef = useRef(null);
        processingStatusRef.current = processingStatus[0];
        
        useEffect(() => {
            dispatch(fetchDeliveryStatus({ client_id: user.id }));
    
            // Fetching data changes after 1 Minute
            const interval = setInterval(() => {
                if (processingStatusRef.current === "DELIVERED") {
                    clearInterval(interval)
                } else {
                    dispatch(fetchDeliveryStatus({ client_id: user.id }));
                }
            }, 60000);
    
        return () => clearInterval(interval);
      }, [dispatch]);
    }
    

    【讨论】:

    • 谢谢阿信。只是为了添加一些上下文,这就是我使用 useSelector 的方式; ``` const state = useSelector((state) => state); const { deliveryStatus } = 状态; const processingStatus = deliveryStatus.map( (status) => status.delivery_status ); ``` processingStatus 返回一个数组,所以我选择第一个索引 [0] 中的那个,因此 processingStatus[0]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多