useState 实现原理

2021-11-19  本文已影响0人  Lucien_d70a

useState

function App() {
  const [x, setX] = useState(0)
  return <div>
    <h1>{x}</h1>
    <button onClick={() => setX(x + 1)}>+1</button>
  </div>
}

简单的实现一个useState

const rootElement = document.getElementById("root");

const render = () => {
    ReactDOM.render(<App/>, root)
}
const useState = (initialValue) => {
    function setState(newState) {
      render()
    }
    return [state, setState]
}

function App() {
  const [n, setN] = useState(0);

  return (
    <div className="App">
      <h1>{n}</h1>
      <button onClick={() => setN(n + 1)}>+1</button>
    </div>
  );
}
let state;
const render = () => {
    ReactDOM.render(<App/>, root)
}
const useState = (initialValue) => {
    state = state === undefined ? initialValue : state
    function setState(newState) {
      state = newState
      render()
    }
    return [state, setState]
}
let state = []
let index = 0
const render = () => {
    index = 0
    ReactDOM.render(<App/>, root)
}
const useState = (initialValue) => {
    const currentIndex = index
    state[currentIndex] = state[currentIndex] === undefined 
        ? initialValue 
        : state[currentIndex]
    function setState(newState) {
      state[currentIndex] = newState
      render()
    }
    index = index + 1
    return [state[currentIndex], setState]
}

从简单例子,深入一点了解。

上一篇 下一篇

猜你喜欢

热点阅读