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(, rootElement);

function App() {
  const [n, setN] = useState(0);
  const [m, setM] = useState(0);
  return (
    

{n}

{m}

); } ReactDOM.render(, rootElement);

你可能感兴趣的:(React hook的useState 简易实现)