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的调用顺序必须完全一致。
网友评论