欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

最简单——最简单的实现useState

程序员文章站 2022-03-04 14:10:57
...

一个state简单实现

import React from 'react';
import ReactDOM from 'react-dom';

let _state;

function myUseState(initialValue) {
    _state = _state || initialValue;
    function setState(newState) {
        _state = newState;
        render();
    }
    return [_state, setState]
}
const render = () => ReactDOM.render(<App />,  document.getElementById('root'))

function App(params) {
    const [n, setN] = myUseState(0);
    return (
        <div>
          <h1  >123123</h1>
            <p>{n}</p>
            <button  onClick={() => { setN(n + 1)}}>+1</button>
        </div>
    )
}

ReactDOM.render(
  <App />,
  document.getElementById('root'));

多个state

  import React from 'react';
  import ReactDOM from 'react-dom';

  let _state = [];
  let index = 0;

  function myUseState(initialValue) {
    const currentIndex = index;
    console.log('currentINdex', currentIndex)
    _state[currentIndex] = _state[currentIndex] || initialValue;
    function setState(newState) {
      _state[currentIndex] = newState;
      render();
    }
    index += 1;
    return [_state[currentIndex], setState]
  }
  const render = () =>  { 
    index = 0;
    ReactDOM.render(<App />,  document.getElementById('root'))
  }

  function App(params) {
    const [n, setN] = myUseState(0);
    const [m, setM] = myUseState(0);
    return (
      <div>
        <h1  >123123</h1>
          <p>{n}</p>
          <button  onClick={() => { setN(n + 1)}}>+1</button>
          <p>{m}</p>
          <button  onClick={() => { setM(m + 1)}}>+1</button>
      </div>
    )
  }

  ReactDOM.render(
    <App />,
    document.getElementById('root'));