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