-
Notifications
You must be signed in to change notification settings - Fork 21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
react解析 React.Children(二) #8
Labels
Blog
文章
Comments
This was referenced Aug 10, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
react解析 React.Children(二)
在React实际开发中,
React.Children
这个API我们虽然使用的比较少, 但是我们通过这个API可以操作children
, 可以查看文档我们来看下这个API的神奇用法
下面可以看一下它在项目中的实际用法:
控制台打印渲染的节点和props,如下图
从上图可以得知,通过 c => [[c, c]] 转换以后节点变为了:
我们需要定位到 ReactChildren.js 文件,查看代码, React.Children.map 方法实际就是mapChildren函数,让我们来看看 mapChildren 内部到底是如何实现的吧!
getPooledTraverseContext 和 releaseTraverseContext 中的代码, 引入了对象重用池的概念。这个概念的用处就是维护一个大小固定的对象重用池,每次从这个池子里取一个对象去赋值,用完之后就将对象上的属性清空然后丢回池子。维护这个池子的用意就是提高性能,避免频繁创建销毁多属性对象。
虽然在调用了traverseAllChildren函数,实际调用的是traverseAllChildrenImpl方法。
这个函数首先 判断 children 的类型, 若children为数组,继续递归调用
traverseAllChildrenImpl
,直到处理成单个可渲染的节点,然后调用才能调用callback,也就是mapSingleChildIntoContext
。最后让我们来读一下 mapSingleChildIntoContext 函数的实现。
mapSingleChildIntoContext
函数其实就是调用React.Children.map(children, callback)
中的callback. 如果map之后还是数组, 那么再次进入mapIntoWithKeyPrefixInternal, 那么这个时候我们就会再次从对象重用池里面去获取context, 而对象重用池的意义也就是在这里, 如果循环嵌套多了, 可以减少很多对象创建和gc的损耗. 如果不是数组, 判断返回值是否是有效的 Element, 验证通过的话就 clone 一份并且替换掉 key, 最后把返回值放入 result 中, result 其实也就是 mapChildren 的返回值.下面是运行顺序:
更多内容:
react解析: React.createElement(一)
参考:
yck: 剖剖析 React 源码
Jokcy 的 《React 源码解析》: react.jokcy.me/
ps: 顺便推一下自己的个人公众号:Yopai,有兴趣的可以关注,每周不定期更新,分享可以增加世界的快乐
The text was updated successfully, but these errors were encountered: