cyan33 / learn-react-source-code

Build react from scratch (code + blog)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

为什么setState不会改变Element,而props会呢?

strongcode9527 opened this issue · comments

感谢博主的分享,看后感觉收获很多。但当我看到第四篇博文,有一点疑问那就是:其中提到一种是组件的 props 发生变化,这会改变 Element 数据,而 state 的改变却并不会改变 Element。这是为什么呢?

谢谢!这点我可能说的有点容易引起误解了。

对于一个组件自身来说,最终 render 出的节点是这样来决定的: (props, state) => dom node,但是回顾一下 Element 的数据结构:

{
  type,
  props
}

其中并不包含 state。所以这也是为什么 state 也被称为 local state。因为从 Element 这个层级是看不到组件内部的 state 的。所以我们可以通过判断 prevElement === nextElement 来判断是 props 变了还是 state 变了。

@cyan33 感谢博主的解答,我再好好地看一遍,希望能把整个教程跟下来!

nice! 有疑惑的欢迎继续交流 @strongcode9527