gpt4 book ai didi

javascript - 为什么这个 setState 意外地传递了旧值?

转载 作者:行者123 更新时间:2023-12-02 17:58:30 26 4
gpt4 key购买 nike

我有这个父组件( Parent ),它包含一个内部组件( InnerComp )(用于组织代码)。内部组件有另一个嵌套组件( Comp ),我从另一个文件导入它。更新Parent的状态来自Comp ,我正在传递setParentCount通过Comp中的prop函数

function Parent() {
const [parentCount, setParentCount] = useState(0);

const InnerComp = () => (
<>
<h2>necessary inner comp</h2>
<hr />
<Comp setParentCount={setParentCount} />
</>
);

return (
<>
<h1>Parent</h1>
<hr />
<InnerComp />
<p>parent comp count = {parentCount}</p>
</>
);
}

Comp也有自己的状态。 Comp 中的“单击”按钮调用handleClick单击时的功能。 handleClick函数正在尝试更新 CompParent的状态。但似乎compCount没有更新。

function Comp({ setParentCount }) {
const [compCount, setCompCount] = useState(0);

useEffect(() => {
console.log(compCount);
}, [compCount]);

function handleClick() {
setCompCount((prev) => prev + 1);

setParentCount((prev) => prev + 1);
}

return (
<>
<h3>child comp</h3>
<button onClick={handleClick}>Click</button>
<p>child comp count = {compCount}</p>
</>
);
}

我添加了useEffect以及compCountComp 。每次我点击按钮时它都会记录。但初始值相同。表示setCompCount函数每次都设置旧值。我想知道为什么会发生这种情况。

当我添加InnerComp时直接在Parent里面的JSX它不需要制作新的内部组件,而是可以正常工作。但我有点需要InnerComp让我的代码井井有条。

我知道我可以让它与useContext一起工作,但我认为这里的上下文会让这个小组件变得非常重。

Here是一个代码沙盒

最佳答案

您的问题是您在 Parent 组件中定义 InnerComp 。这意味着每次您的 Parent 组件重新渲染时,它都会重新定义 InnerComp 函数,每次都会创建一个新的组件类型。换句话说,在每次重新渲染 Parent 时,InnerComp 代表一个全新的组件,使用它将替换以前版本的 InnerComp 并启动使用默认状态。

要解决此问题,您应该将 InnerComp 的定义移到 Parent 组件之外,并将 Parent 的任何依赖项作为 props 传入InnerComp 像这样:

const InnerComp = ({ setParentCount }) => (
<>
<h2>necessary inner comp</h2>
<hr />
<Comp setParentCount={setParentCount} />
</>
);

function Parent() {
const [parentCount, setParentCount] = useState(0);
return (
<>
<h1>Parent</h1>
<hr />
<InnerComp setParentCount={setParentCount} />
<p>parent comp count = {parentCount}</p>
</>
);
}

这样,InnerComp 就不会不断被重新定义,并且每次重新渲染时都表示相同的组件类型,从而保留其内部状态。

这是一个CodeSanbox with a working example .

关于javascript - 为什么这个 setState 意外地传递了旧值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75048021/

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