gpt4 book ai didi

javascript - 组件未使用 'useEffect' Hook 在 React 中重新呈现

转载 作者:行者123 更新时间:2023-12-05 03:54:28 24 4
gpt4 key购买 nike

我正在创建一个只应在用户首次访问网站时出现的弹出模式。为此,我使用 useEffect Hook 来做两件事:1.) 检查是否已经设置了 cookie,(如果没有设置 cookie)2.) 基于该检查,更新isCookie 状态为真/假。

然后我将 isCookie 状态值作为 prop 传递给模态组件,模态组件将使用 isCookie 状态来确定是否显示模态。

问题在于:模态框仅基于 useState 初始值进行渲染。即使在 useEffect 中更新了状态之后,模态框也不会重新渲染。我可以通过控制台日志确认状态正在更新,但我不知道如何让模态重新呈现。

useEffect 中的 cookie 检查和放置:

const [cookie, setCookie] = useState({isCookie:true})
const newCookie = "visited=true; max-age=604800";

useEffect(() => {
if (!document.cookie.split(';').some((item) => item.trim().startsWith('visited='))) { //check to see if a cookie has been placed, if not this is a 'first visit'
setCookie({isCookie:false});
document.cookie = newCookie; //place cookie on first visit
}
}, [])



<PopUp cookie={cookie.isCookie}/>

弹出/模态组件的相关部分:

const PopUp = (props) => {

/*if a cookie is present, the initial state of the modal is hidden, otherwise it's set to 'open' or shown*/

const initialModalState = props.cookie ? {open: false} : {open: data.markdownRemark.frontmatter.show}

const [modal, setModal] = useState(initialModalState)
}

最佳答案

useEffect 确实会通过状态更改重新呈现模态,但重新呈现不会重置其中呈现的组件的状态变量(如果你想到一个带有一个受控组件。)只有重新安装才能做到这一点。

因此,当您将模态设置为 useState(intialModalState) 时,它将始终依赖于它接收到的初始 prop 而不是其他任何东西。

要在重新渲染发生时将 prop 同步到 state,您需要在 child 内部使用一个 useEffect 来监听 prop 的变化:

const initialModalState = props.cookie ? {open: false} : {open: data.markdownRemark.frontmatter.show}

const [modal, setModal] = useState(initialModalState)

useEffect(() => {
setModal(props.cookie ? {open: false} : {open: data.markdownRemark.frontmatter.show})
}, [props.cookie]);

关于javascript - 组件未使用 'useEffect' Hook 在 React 中重新呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60963566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com