react-hooks源码第一天useState

import React from 'react';
import ReactDOM from 'react-dom';
let hooksIndex = 0
const hooksState = []
const useState = (initialValue)=>{
  hooksState[hooksIndex] = hooksState[hooksIndex] || initialValue 
  let currentIndex = hooksIndex
  function setFunction(state){
    hooksState[currentIndex] = state
    render()
  }
  return [hooksState[hooksIndex++],setFunction]
}
const Couter = ()=>{
  const [number1,setNumber1] = useState(0)
  const [number2,setNumber2] = useState(0)
  return <div>
    <p>{number1}</p>
    <button onClick={()=>{setNumber1(number1+1)}}>btn1</button>
    <p>{number2}</p>
    <button onClick={()=>{setNumber2(number2+1)}}>btn2</button>
  </div>
}



const render = ()=>{
  hooksIndex = 0
  ReactDOM.render(
    <Couter/>,
    document.getElementById('root')
  )
}
render()


这里面最核心精妙之处在于,useState(0)会暴露一个number值和一个setFunction,其中每使用一个useState,他们暴露出来的number和setFunction都不一样,而且互相不影响,而且是闭包。把函数暴露在了外面,而且这个闭包还分别保留了哪一个useState的索引,让我们每次调用索引为几的useState里面的setFunction时,setFunction都知道去改变索引为几的值。当然这些值都是保存在了数组里面,所以setFunction才能在数组里面根据索引改变相应的值。

setFunction里面:

每次改变了新的值,我们先render ,调用render我们就会重新把hooksIndex置为0,而且<Couter/>组件会重新渲染,那面也就说const [] =useState()      那两行代码会重新执行,所以此时又回到了第一次useState

最后每次抛出 [state,setFunction],当然这里state其实是arr[index]这种形式,为啥要加1,因为下次,抛出自动索引加1   ,为啥又保留了currentIndex,这步完全是为了闭包,把索引保存出去

ok今天的分享就到这里了!!!!!!

原文地址:https://www.cnblogs.com/MDGE/p/13671132.html