javascript - React 如何保持组件状态?
问题描述
这是一个关于 react.js 内部的问题。以下是我对虚拟 dom 的理解。
old (rendered from component <X/>) new (rendered from component <X/>)
null <div>
<AnotherComponent/> <- state {count:0}
<p>{this.state.text}</p>
</div>
在比较过程中,该函数发现旧快照为空。我们创建我们的元素,以及来自组件的元素<AnotherComponent/>
。
old (rendered from component <X/>) new (rendered from component <X/>)
<div> <div>
<AnotherComponent/> <- state {count:1} <AnotherComponent/> <- state {count:0} ?
<p>Lorem ipsum</p> <p>Lorem ...</p> <- state updates
</div> </div>
假设<X/>
组件第二次更新,并且<AnotherComponent/>
在父组件更新之前更改了其状态。
好的,我比较两个快照,应用更改。但<AnotherComponent/>
将重置其状态,我将拥有{count:0}
而不是{count:1}
.
react.js 或任何其他用于构建 ui 的声明性 js 库如何做一些事情。也许我搞错了。
我想我需要获取旧组件的状态并将其分配给一个新组件。这是正确的方法吗?谢谢!
解决方案
据我所知,React 使用闭包来捕获重新渲染之间的状态。
推荐阅读
- react-native - 添加嵌套屏幕 react-native 后如何隐藏导航标题
- dart - 创建无状态小部件时如何运行代码
- interop - Blazor 互操作导致 LOS 溢出
- c++ - 我的冒泡排序在数组中引入了“0”的值
- vbscript - 在浏览器中显示注释代码块的经典 ASP 页面
- firebase - 推送通知在带有 firebase 的 Angular 7 应用程序中不起作用
- java - Java,解压缩文件名中带有德语字符的文件夹
- javascript - 在 reactjs 中渲染嵌套对象
- go - 如何通过 Gmail Go SDK 将 html 模板正文作为电子邮件发送?
- docker - 将代理服务器 Docker 化,以便我可以通过 vhost 连接到容器。可能吗?