自己做一个useState

43 阅读1分钟
import React from 'react';
import {compareArraysAsSet} from '@testing-library/jest-dom/dist/utils';
import ReactDOM from 'react-dom/client';


const root = ReactDOM.createRoot(document.getElementById('root'));
let _state = [];
let index = 0;
const myUseState = (initialValue) => {
    const currentIndex = index;
    _state[currentIndex] = _state[currentIndex] === undefined ? initialValue : _state[currentIndex];
    //_state = _state || initialValue;
    const setState = (newValue) => {
        _state[currentIndex] = newValue;
        root.render(
            <App/>
        );
    };
    index += 1;
    return [_state[currentIndex], setState];
};

const App = () => {
    index = 0;
    const [n, setN] = myUseState(0);
    const [m, setM] = myUseState(0);
    console.log(`n:${n},m:${m}`);
    return (
        <div className="App">
            <p>{n}</p>
            <p>
                <button onClick={() => setN(n + 1)}>n+1</button>
            </p>
            <p>{m}</p>
            <p>
                <button onClick={() => setM(m + 1)}>m+1</button>
            </p>
        </div>
    );
};

export default App;