首页 > 解决方案 > 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 库如何做一些事情。也许我搞错了。

我想我需要获取旧组件的状态并将其分配给一个新组件。这是正确的方法吗?谢谢!

标签: javascriptreactjsuser-interfacecomponentsvirtual-dom

解决方案


据我所知,React 使用闭包来捕获重新渲染之间的状态。


推荐阅读