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

一个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(,  document.getElementById('root'))

function App(params) {
    const [n, setN] = myUseState(0);
    return (
        

123123

{n}

) } ReactDOM.render( , 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(,  document.getElementById('root'))
  }

  function App(params) {
    const [n, setN] = myUseState(0);
    const [m, setM] = myUseState(0);
    return (
      

123123

{n}

{m}

) } ReactDOM.render( , document.getElementById('root'));

你可能感兴趣的:(技术栈笔记,前端技术栈,JavaScript,react,hooks)