React hook的useState 简易实现

模拟useState

要点

  • _下划线代表内部的变量
  • const currentIndex = _index; 缓存当前的index
import React from "react";
import ReactDOM from "react-dom";
const rootElement = document.getElementById("root");

let _initialState; // 
let _index = 0;
let initialArr = [];
function useState(defaultState){
  _initialState = initialArr[_index] || defaultState;
  const currentIndex = _index; // 缓存当前的index
  const setValue = (val) => {
    initialArr[currentIndex] = val;
    _index = 0;
    render();
  }
  _index +=1;
  return [_initialState,setValue];
}

const render = () => ReactDOM.render(<App />, rootElement);

function App() {
  const [n, setN] = useState(0);
  const [m, setM] = useState(0);
  return (
    <div className="App">
      <p>{n}</p>
      <p>{m}</p>
      <p>
        <button onClick={() => setN(n + 1)}>+1</button>
        <button onClick={() => setM(m + 1)}>+1</button>
      </p>
    </div>
  );
}

ReactDOM.render(<App />, rootElement);

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容