js 模拟React Hooks的useState

2021年02月23日,原生js模拟hooks的useState

let _state = [];
let index = 0;
const myUseState = (initialState) => {
    var currentIndex = index; // 保存index
   _state[currentIndex] = !_state.length
       ? initialState
       : _state[currentIndex];
    
    function setState(newState) {
        _state[currentIndex] = newState;
    }
    index = index + 1;
    return [_state[currentIndex], setState];
}
const render = (props) => {
   index = 0; //  
   const [value, setValue] = myUseState(1);
   console.log(value);
    
   return setValue
}
let f = render();
f(undefined);
render();
f(0);
render();
f(5);
render();
f(null);
render();

 

posted @ 2021-07-13 11:36  Bruce_Grace  阅读(121)  评论(0编辑  收藏  举报