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(<App />, document.getElementById("root"));
};
// 使用myUseState
const App = () => {
  const [n, setN] = myUseState(0);
  const [m, setM] = myUseState(0);
  return (
      <div classNam="App">
         <p>n:{n}</p>
         <button onClick={()=>{setN(n+1)}}>n+1</button> 
         <p>m:{m}</p>
         <button onClick={()=>{setM(m+1)}}>n+1</button> 
      </div>
      );
};
ReactDOM.render(<App />, document.getElementById("root"));

张长长
67 声望4 粉丝