项目结构

  • yarn dev
    1
    2
    3
    4
    5
    .
    ├── README.md
    ├── index.html
    ├── package.json
    ├── useState.jsx

package.json

1
2
3
4
5
6
7
8
{
"devDependencies": {
"vite": "^2.9.5"
},
"scripts": {
"dev": "vite"
}
}

index.html

1
2
3
4
5
6
<body>
<div id="app"></div>
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
<script type="module" src="./useState.jsx"></script>
</body>

useState.jsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const myReact = (() => {
const states = []
const stateSetters = [];
let stateIndex = 0

// let _state;
// function useState(initialState) {
// _state = _state === undefined ? initialState : _state;
// const _setState = (newState) => {
// if (typeof newState === 'function') {
// _state = newState(_state)
// } else {
// _state = newState
// }

// render()
// }
// return [_state, _setState]
// }

function createState(initialState, stateIndex) {
return states[stateIndex] !== undefined ? states[stateIndex] : initialState;
}

function createStateSetter(stateIndex) {
return function (newState) {
if (typeof newState === 'function') {
states[stateIndex] = newState(states[stateIndex])
} else {
states[stateIndex] = newState
}
render()
}
}

function useState(initialState) {
states[stateIndex] = createState(initialState, stateIndex)

if (!stateSetters[stateIndex]) {
stateSetters.push(createStateSetter(stateIndex))
}

const _state = states[stateIndex]
const _setState = stateSetters[stateIndex]

stateIndex++;

return [_state, _setState]
}


function render() {
stateIndex = 0;
ReactDOM.render(
<App />,
document.querySelector('#app')
)
}

return {
useState
}
})();

const { useState } = myReact;
// const { useState } = React;

const App = () => {

const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false)

return (
<div>
<h1>{count}</h1>
<h1>{flag ? 'open' : 'close'}</h1>
<button onClick={() => setCount(count + 1)}>Add</button>
<button onClick={() => setCount(count => count - 1)}>sub</button>
<button onClick={() => setFlag(flag => flag = !flag)}>{flag ? '关闭' : '打开'}</button>
</div>
)
}

ReactDOM.render(
<App />,
document.querySelector('#app')
)