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