zoukankan      html  css  js  c++  java
  • 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今天的分享就到这里了!!!!!!

  • 相关阅读:
    CH02 FPGA设计Verilog基础笔记(二)
    同一个按键短按与长按的区别触发
    树莓派 -- 输入设备驱动 (key) 续2: 转载 Setting up a GPIO-Button “keyboard” on a Raspberry Pi
    树莓派 -- 输入设备驱动 (key) 续1
    树莓派 -- 输入设备驱动 (key)
    树莓派 -- 按键 (key)使用BCM2835 gpio library
    leds-gpio driver 续1
    leds-gpio driver
    使用CSDN-markdown编辑器
    树莓派
  • 原文地址:https://www.cnblogs.com/MDGE/p/13671132.html
Copyright © 2011-2022 走看看