React hook的useState 简易实现

2021-06-09  本文已影响0人  Nicklzy

模拟useState

要点

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);

上一篇 下一篇

猜你喜欢

热点阅读