首页 > 解决方案 > 我的三元运算符与应该发生的情况相反

问题描述

我正在创建一个模式来显示它是否是第一次加载页面。为了存储我使用本地存储的信息。

在我的产品页面上,我为 localStorage 项目“firstLoad”创建了一个变量,如果未找到结果,则默认返回 true。然后我将 localStorage 项目“firstLoad”设置为 false。我已经记录了变量,这不会在相同的负载(这是我想要的)上改变它们,但是在模态组件上,三元运算符具有相反的效果。

产品.js:

let firstLoad = localStorage.getItem('firstLoad') || true

  const [showModal, setShowModal] = useState(firstLoad)

  useEffect(() => {
    localStorage.setItem('firstLoad', false)
  })
  return (
    <Layout>
      <SEO title="Products" />

      {/* Need to keep an eye on this, having the opposite behaviour to what is expected */}
      <Modal showModal={showModal} setShowModal={setShowModal}>
        <h2>OCD DOE-MAX</h2>
        <p>Available in 3 forms and multiple fragrances, we do one product and do it well.</p>
        <p>Click on any active button to see a description of the type or fragrance</p>
        <button onClick={() => setShowModal(false)}>EXPLORE FRAGRANCES</button>
      </Modal>

模态的.js:

const Modal = ({ children, showModal, setShowModal }) => {

    const modalSpring = useSpring({
        opacity: showModal ? 1 : 0,
        scale: showModal ? 1 : 0.4
    })

    const backdropSpring = useSpring({
        opacity: showModal ? 1 : 0
    })

    return (
        <div className="modal-wrapper">
            <animated.div className="backdrop" style={backdropSpring} onClick={() => setShowModal(false)} />
            <animated.div className="modal" style={modalSpring}>
                <span style={{ display: 'flex', justifyContent: 'center' }}>
                    <button onClick={() => setShowModal(false)} class="exit">X</button>
                </span>
                {children}
            </animated.div>
        </div >

    )
}

标签: javascriptreactjsgatsbyconditional-operator

解决方案


发生这种情况是因为 localStorage 项目作为字符串返回。我通过在 localStorage 项目周围使用 JSON.parse() 来扭转这一点。

产品.js:

let firstLoad = JSON.parse(localStorage.getItem('firstLoad')) || true

  const [showModal, setShowModal] = useState(firstLoad)

  useEffect(() => {
    localStorage.setItem('firstLoad', "false")
  })

推荐阅读