【react】手写useState

let _state=[];
let index=0;
function myUseState(initialValue) {
  int currentIndex=index;    //引入中间变量currentIndex就是为了保存当前操作的下标index。
  _state[currentIndex] = _state[currentIndex]===undefined? initialValue:_state[currentIndex];
  const setState = (newValue) => {
    _state[currentIndex] = newValue; 
    render(); 
  };
  index+=1;// 每次更新完state值后,index值+1
  return [_state[currentIndex], setState];
}
const render = () => {
  index=0;    //重要的一步,必须在渲染前后将index值重置为0,不然index会一种增加1
  ReactDOM.render(, document.getElementById("root"));
};
// 使用myUseState
const App = () => {
  const [n, setN] = myUseState(0);
  const [m, setM] = myUseState(0);
  return (
      

n:{n}

m:{m}

); }; ReactDOM.render(, document.getElementById("root"));

你可能感兴趣的:(react.js)