React 问答游戏中满足获胜条件时模态会打开两次

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

我正在构建一个 React 测验应用程序,一旦所有答案都正确或用户失去所有生命,就会出现一个模式。然而,尽管我尝试控制状态,但模式会打开两次而不是一次。我尝试使用状态变量 showModal 管理模式显示。我还尝试添加一个标志来控制它,但问题仍然存在。是什么原因导致此问题?如何解决?

const handleModalClose = () => {
  setShowModal(false);
};

const Modal = ({ isOpen, onClose }) => {
  const modalRef = useRef();

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (modalRef.current && !modalRef.current.contains(event.target)) {
        onClose();
      }
    };

    document.addEventListener("mousedown", handleClickOutside);

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [onClose]);

  if (!isOpen) return null;
  if (correctAnswersCount >= 9) {
    confetti({
      particleCount: 100,
      spread: 70,
      origin: { y: 0.6 },
    });
  }

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-content" ref={modalRef}>
        {correctAnswersCount > 9 && (
          <h2>Congrats! You've found all the correct answers!</h2>
        )}
        <h3>
          <b>Score</b>
        </h3>

        <div className="answer-progress-container">
          <div className="answer-progress">
            <div
              className="answer-progress-bar"
              style={{ width: `${(correctAnswersCount / 10) * 100}%` }}
            >
              {correctAnswersCount}/10
            </div>
          </div>
          <p className="streak-p">Current Streak: {streakCounter}</p>
        </div>
      </div>
      <button className="modal-close" onClick={onClose}>
        x
      </button>

我称之为模态的部分,希望现在更清楚了;

{showModal && (
        <Modal
          isOpen={showModal}
          onClose={handleModalClose}
        />
      )}
javascript reactjs
1个回答
0
投票

一种选择是使用

useEffect
检查
correctAnswersCount
lives

useEffect(() => {
  // assuming you also have state called 'lives'
  if (correctAnswersCount >= 9 || lives === 0) {
    setShowModal(true);
  }
}, [correctAnswersCount, lives]);

// other parts of the code
© www.soinside.com 2019 - 2024. All rights reserved.