【问题标题】:How do I toggle classes in GatsbyJS depended on a cookie?如何在 GatsbyJS 中切换依赖于 cookie 的类?
【发布时间】:2019-05-13 07:12:25
【问题描述】:

我想为我的 Gatsby 爱好页面做一个简单的 cookie 通知,而不使用额外的 cookie npm 包。

我使用“universal-cookie”npm 包成功设置了 cookie。当我单击同意横幅的“关闭”按钮时,我更改了状态,它确实隐藏了横幅。但是当我现在重新加载我的页面时,横幅仍然显示,即使 cookie 和状态设置正确(通过 console.log 检查)。

import React from 'react'
import Cookie from 'universal-cookie'

const cookie = new Cookie()

class CookieNotice extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      active: cookie.get('viewed_cookie_notice'),
    }
    this.toggleActiveClass = this.toggleActiveClass.bind(this)
  }

  componentDidMount() {
    this.setState({ active: cookie.get('viewed_cookie_notice') })
  }

  toggleActiveClass() {
    cookie.set('viewed_cookie_notice', true, { path: '/', expires: new Date(Date.now() + 2592000) })
    this.setState({ active: cookie.get('viewed_cookie_notice') })
  }

  render() {
    const { active } = this.state
    return (
      <div id="cookie-notice" className={active ? 'hidden' : null}>
          <button type="button" id="close-cookie" onClick={this.toggleActiveClass}>
            Close!
          </button>
        </div>
      </div>
    )
  }
}
export default CookieNotice

我只想永久隐藏 cookie 横幅,如果用户已关闭 cookie 横幅并且每次重新访问页面时都不向他显示。

【问题讨论】:

    标签: javascript reactjs cookies gatsby


    【解决方案1】:

    在你的构造函数中,改变状态中active的值。

    constructor(props) {
      super(props);
      this.state = { active: true };
    }
    

    通过将active的值设置为true,意味着当组件第一次加载时,banner会被隐藏,然后在componentDidMount中调用setState,就会得到cookie 然后用正确的值重新渲染。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 2015-10-22
      相关资源
      最近更新 更多