一、基础知识 React API 一览

1.10 Hooks

参考文章:https://juejin.im/post/5be3ea136fb9a049f9121014

demo:

/**
 * 必须要react和react-dom 16.7以上
 */

import React, { useState, useEffect } from 'react'

export default () => {
  const [name, setName] = useState('jokcy')

  useEffect(() => {
    console.log('component update')

    return () => {
      console.log('unbind')
    }
  }, [])

  return (
    <>
      <p>My Name is: {name}</p>
      <input type="text" value={name} onChange={e => setName(e.target.value)} />
    </>
  )
}

1.11 React.children

用法文章推荐:https://www.jianshu.com/p/d1975493b5ea

源码: https://github.com/KieSun/Dream/issues/18

https://juejin.im/post/5cd557bbf265da03a97b0780

demo:

import React from 'react'

function ChildrenDemo(props) {
  console.log(props.children)
  console.log(React.Children.map(props.children, c => [c, [c, [c, c]]]))
  return props.children
}

export default () => (
  <ChildrenDemo>
    <span>1</span>
    <span>2</span>
  </ChildrenDemo>
)

如果map的第二个参数返回的是一个数组,不管是多少层的,都会展开成一层的一个一维数组。

源码流程图:

 首先在mapInfoWithKeyPrefixInternal中去对象重用池中取一个context,用完了会还回来的,然后到了traverseAllChildrenImpl去查看Children是不是一个数组或者一个可以遍历的对象,判断是不是多个节点,如果是单个节点,就到了mapSingleChild(不是的话就递归),这里调用调用我们自己传入的callBack函数。我们自己的callBack函数可能返回一个数组,或者是一个新的节点,这样我们就拿到一个map之后的节点,如果又是一个数组,又回到mapIntoWithKeyPrefixInternal.这样递归的话,就解释了上面的那个结果。

为什么要用重用池尼?因为在判断我们的callBack函数是不是返回数组的时候,如果是就递归调用mapIntoWithKeyPrefixInternal,这里面又得用到重用池,因此如果是返回两层数组,就得用到两个context,所以需要重用池。

1.12、React.memo&&React.Fragment&&React.cloneElement&&React.createFactory

React.memo用法参考:https://www.jianshu.com/p/b3d07860b778

React.Fragment用法参考:https://www.reactjscn.com/docs/fragments.html

React.createElement用法参考:https://www.jianshu.com/p/2ccf0cd14388

原文地址:https://www.cnblogs.com/QianDingwei/p/11072363.html