【问题标题】:How React keeps the component state?React 如何保持组件状态?
【发布时间】:2020-07-08 11:42:13
【问题描述】:

这是一个关于 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>

在比较过程中,该函数发现旧快照为空。我们创建我们的元素,以及来自组件 &lt;AnotherComponent/&gt; 的元素。

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>

假设&lt;X/&gt; 组件第二次更新,&lt;AnotherComponent/&gt; 在父组件更新之前已更改其状态。

好的,我比较两个快照,应用更改。但&lt;AnotherComponent/&gt; 将重置其状态,我将拥有{count:0} 而不是{count:1}

react.js 或任何其他用于构建 ui 的声明性 js 库如何做一些事情。可能是我搞错了。

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

【问题讨论】:

  • 组件在内部状态改变或传入的 props 改变时会创建虚拟 DOM。 React 将此与之前的渲染周期进行比较,并相应地更新 DOM。除非包装在 React.memo 中,否则函数式组件将始终重新渲染。组件内部状态在使用 context 或 redux connect/useSelector 以及 context 或 connect/useSelector 更改的结果时也会发生变化。

标签: javascript reactjs user-interface components virtual-dom


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-02-25
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 2018-11-19
    相关资源
    最近更新 更多