美文网首页
React hook的useState 简易实现

React hook的useState 简易实现

作者: Nicklzy | 来源:发表于2021-06-09 10:57 被阅读0次

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

相关文章

网友评论

      本文标题:React hook的useState 简易实现

      本文链接:https://www.haomeiwen.com/subject/xkfeeltx.html