胖蔡叨叨叨
你听我说

useState原理解析

本文转载自https://www.jianshu.com/p/a36fb3d3885f,如有侵权,请联系删除

最简单的useState实现

看下面的代码:

    const Demo = ()=> {
      const [n,setN] = React.useState(0)
      return <div>
        {n}
        <button onClick={()=> {setN(n+1)}}>点我+1</button>
      </div>
    }
    const rootElement = document.getElementById("app")
    ReactDOM.render(<Demo />, rootElement);
做了哪些事:

首次渲染:render()——得到Demo组件——调用Demo组件——得到虚拟div——创建真实的div

点击button后:调用setN(n+1)——再次render()——得到Demo组件——调用Demo组件——得到虚拟div——使用DOM Diff对比——更新真实的div

往后一次重复第二次的操作

分析:

state:每个组件都应该有自己的数据state,
setN:setN一定会修改数据state,将n+1存入state,然后重新render(),再次渲染
useState:useState肯定会从state读取n的最新值

尝试实现React.useState

    let _state 
    const myUseState = (initState) => {
      _state = _state ===undefined ? initState : _state 
      const setState = (newValue =>{
        _state = newValue
        render()
      })
      return [_state,setState]
    }
    const render =()=>{
      ReactDOM.render(<Demo />, rootElement);
    } 
    const Demo = ()=> {
      const [n,setN] = myUseState(0)
      console.log('n变了');
      console.log(`n的值是: ${n}`);
      return <div>{n}
          <button onClick={()=> {setN(n+1)}}>点我+1</button>
        </div>
    }
    const rootElement = document.getElementById("app")
    ReactDOM.render(<Demo />, rootElement);

多点几次,打印的结果看下图

image.png

打印的结果也确实对,却又一个很大的问题:如果一个组件用了两个useState怎么办?

    let _state 
    const myUseState = (initState) => {
      _state = _state ===undefined ? initState : _state 
      const setState = (newValue =>{
        _state = newValue
        render()
      })
      return [_state,setState]
    }
    const render =()=>{
      ReactDOM.render(<Demo />, rootElement);
    } 
    const Demo = ()=> {
      const [n,setN] = myUseState(0)
      const [m,setM] = myUseState(0)
      return <div>{n}
          <button onClick={()=> {setN(n+1)}}>点我+1</button>
          <br/>
          {m}
          <button onClick={()=> {setM(m+1)}}>点我+1</button>
        </div>
    }
    const rootElement = document.getElementById("app")
    ReactDOM.render(<Demo />, rootElement);

把上面的代码运行,你会发现,无论你点击哪个button,n和m都会+1,

现在我们来对它改进,_state不能直接让它等于一个值,而是让它等于很多值,只有对象和数组能做到,而对象不太合适,因为_state = {n: 0,m: 0}useState()并不知道变量叫n还是m,只能把它做成数组,比如:_state = [0,0](前面0是n,后面0是m)

    let _state = []
    let index = 0
    const myUseState = (initState) => {
      const currentIndex = index
      _state[currentIndex] = _state[currentIndex] ===undefined ? initState : _state[currentIndex] 
      const setState = (newValue =>{
        _state[currentIndex] = newValue
        console.log(_state);
        render()
      })
      index += 1
      return [_state[currentIndex],setState]
    }
    const render =()=>{
      index = 0
      ReactDOM.render(<Demo />, rootElement);
    } 
    const Demo = ()=> {
      const [n,setN] = myUseState(0)
      const [m,setM] = myUseState(0)
      return <div>{n}
          <button onClick={()=> {setN(n+1)}}>点我+1</button>
          <br/>
          {m}
          <button onClick={()=> {setM(m+1)}}>点我+1</button>
        </div>
    }
    const rootElement = document.getElementById("app")
    ReactDOM.render(<Demo />, rootElement);

最终代码就是上面的代码,用log可以打出_state的值,我们分别点击button让它们+1,看log出的值

image.png

这样,我们自己写的_state是不是就和React的一模一样?

通过实现简单的useState,能让我们更好地理解useState

赞(0) 打赏
转载请附上原文出处链接:胖蔡叨叨叨 » useState原理解析
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏