模拟useState
要点
-
_
下划线代表内部的变量
-
const currentIndex = _index;
缓存当前的index
import React from "react";
import ReactDOM from "react-dom";
const rootElement = document.getElementById("root");
let _initialState; //
let _index = 0;
let initialArr = [];
function useState(defaultState){
_initialState = initialArr[_index] || defaultState;
const currentIndex = _index; // 缓存当前的index
const setValue = (val) => {
initialArr[currentIndex] = val;
_index = 0;
render();
}
_index +=1;
return [_initialState,setValue];
}
const render = () => ReactDOM.render(<App />, rootElement);
function App() {
const [n, setN] = useState(0);
const [m, setM] = useState(0);
return (
<div className="App">
<p>{n}</p>
<p>{m}</p>
<p>
<button onClick={() => setN(n + 1)}>+1</button>
<button onClick={() => setM(m + 1)}>+1</button>
</p>
</div>
);
}
ReactDOM.render(<App />, rootElement);