美文网首页
模拟实现useState

模拟实现useState

作者: percykuang | 来源:发表于2020-06-06 12:24 被阅读0次
import React from 'react'
import App from './App'
import ReactDOM from 'react-dom'

const render = () => {
  index = 0
  ReactDOM.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>,
    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 (
    <div>
      <p>{n}</p>
      <p><button onClick={() => setN(n + 1)}>+</button></p>
      <p>{m}</p>
      <p><button onClick={() => setM(m + 1)}>+</button></p>
    </div>
  )
}

export default Counter

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

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

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

相关文章

网友评论

      本文标题:模拟实现useState

      本文链接:https://www.haomeiwen.com/subject/pdpzzhtx.html