使用 Shopify 应用程序中的结账扩展性添加倒计时器

问题描述 投票:0回答:1

我正在使用 Shopify CLI 3。我已经制作了倒计时计时器,但有一个问题,计时器工作正常,但当我重新加载页面或转到结账的下一步时,计时器重新启动我正在会话中存储数据存储,但这似乎不起作用我也尝试过将数据存储在 cookie、本地存储甚至缓存存储中,但它们似乎都不起作用。

有人可以指导我如何完成这项任务吗?

import React, { useEffect, useState } from 'react';
import {
  render,
  BlockStack,
  Text,
  useSettings,
  View
} from '@shopify/checkout-ui-extensions-react';

render('Checkout::Dynamic::Render', () => <App />);

function App() {

  const calculateEndTime = (timer) => {
    const currentTime = new Date();
    const endTime = new Date(currentTime.getTime() + timer * 60000); // Convert minutes to milliseconds

    return endTime;
  };

  const getRemainingTimeInSeconds = (endTime) => {
    const currentTime = new Date();
    const remainingTimeInSeconds = Math.floor((endTime - currentTime) / 1000);

    return remainingTimeInSeconds >= 0 ? remainingTimeInSeconds : 0;
  };

  const setCookie = (name, value, days) => {
    const expirationDate = new Date();
    expirationDate.setTime(expirationDate.getTime() + days * 24 * 60 * 60 * 1000);
    document.cookie = `${name}=${value}; expires=${expirationDate.toUTCString()}; path=/`;
  };

  const getCookie = (name) => {
    const cookieName = `${name}=`;
    const cookies = document.cookie.split(';');

    for (let i = 0; i < cookies.length; i++) {
      let cookie = cookies[i];
      while (cookie.charAt(0) === ' ') {
        cookie = cookie.substring(1);
      }
      if (cookie.indexOf(cookieName) === 0) {
        return cookie.substring(cookieName.length, cookie.length);
      }
    }

    return '';
  };

  const deleteCookie = (name) => {
    document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
  };

  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const storedEndTime = getCookie('endTime');
    let endTime;

    if (storedEndTime) {
      endTime = new Date(storedEndTime);

      // If the stored end time has already passed, clear it and recalculate the end time
      if (endTime <= new Date()) {
        deleteCookie('endTime');
        endTime = calculateEndTime(isNaN(timer) ? +timer : timer); // Set the timer to 15 minutes
      }
    } else {
      endTime = calculateEndTime(isNaN(timer) ? +timer : timer); // Set the timer to 15 minutes
      setCookie('endTime', endTime.toUTCString(), 1);
    }

    setSeconds(getRemainingTimeInSeconds(endTime));

    const interval = setInterval(() => {
      setSeconds((prevSeconds) => {
        if (prevSeconds <= 0) {
          clearInterval(interval); // Stop the timer
          deleteCookie('endTime');
          return 0;
        }
        return prevSeconds - 1;
      });
    }, 1000);

    return () => {
      clearInterval(interval);
    };
  }, []);

  const formattedTime = React.useMemo(() => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  }, [seconds]);

  return (
    <BlockStack>
      <View>
          <Text>
            {formattedTime}
          </Text>
      </View>
    </BlockStack>
  );
}

export default App;

reactjs shopify shopify-app shopify-api shopify-api-node
1个回答
0
投票

如果您使用的是 Shopify Plus 商店,我建议您将结帐布局选项从三页结帐更新为一页结帐。可以在

Settings > Checkout > Checkout 1 > Customize

找到

对于您的倒数计时器会话存储问题,我在下面添加了一个 JS,这对我有用。我希望它对你有用。

        const COUNTER_KEY = 'my-counter';
        function countDown(i, callback) {
          //callback = callback || function(){};
          timer = setInterval(function() {
            minutes = parseInt(i / 60, 10);
            seconds = parseInt(i % 60, 10);
            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;
            document.getElementById("displayDiv").innerHTML = "Time left " + "0:" + minutes + ":" + seconds;
            if ((i--) > 0) {
              window.sessionStorage.setItem(COUNTER_KEY, i);
              } else {
              window.sessionStorage.removeItem(COUNTER_KEY);
              clearInterval(timer);
              callback();
              }
            }, 1000);
          }
        window.onload = function() {
          var countDownTime = window.sessionStorage.getItem(COUNTER_KEY) || 600; 
// 600 for 10min, 60 for 1min
          countDown(countDownTime, function() {
            $('#myModal').modal('show');
            });
          };
<div id="displayDiv"></div>

© www.soinside.com 2019 - 2024. All rights reserved.