我想为我的 Gatsby Hobby Page 做一个简单的 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 横幅并且每次重新访问该页面时都不会向他显示。
最佳答案
在您的构造函数中,更改状态中 active 的值。
constructor(props) {
super(props);
this.state = { active: true };
}
通过将active
的值设置为true
,意味着当组件第一次加载时,banner会被隐藏,然后通过调用setState
在 componentDidMount
中,它会获取 cookie 的值,然后用正确的值重新渲染。
关于javascript - 如何根据 cookie 在 GatsbyJS 中切换类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56099339/