模拟实现useState

import React from 'react'
import App from './App'
import ReactDOM from 'react-dom'

const render = () => {
  index = 0
  ReactDOM.render(
    
      
    ,
    document.getElementById('root')
  )
}

let state: any[] = []

let index = 0

function myUseState(initState: any) {

  const currentIndex = index

  if (state[currentIndex] === undefined) {
    state[currentIndex] = initState
  }

  function setState(newState: any) {
    state[currentIndex] = newState
    render()
  }

  index++

  return [state[currentIndex], setState]
}

function Counter() {

  const [n, setN] = myUseState(0)

  const [m, setM] = myUseState(0)

  return (
    

{n}

{m}

) } export default Counter

当然,useState的源码不是上面那么写的。但是其中的思想是一致的,无非就是利用数组或者表(源码是链表)将每个state存一下,放在对应的位置。

这种数组方案的缺点也很明显:

在每一次App()执行时,useState的调用顺序必须完全一致。

你可能感兴趣的:(模拟实现useState)