<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
function createStore(reducer) {
let state = {
num: 0
};
let listeners = []
const getState = () => state;
const dispatch = action => {
state = reducer(state, action)
listeners.forEach(listen => listen())
}
const subscribe = listener => {
listeners.push(listener);
return listeners.filter(item => item !== listener);
}
return { getState, dispatch, subscribe}
}
const store = createStore(reducer)
function reducer(state, action) {
if (action.type === 'add') {
return { ...state, num: state.num + action.payload }
}
return state;
}
class App extends React.Component {
add() {
store.dispatch({ type: 'add', payload: 5 })
console.log('state', store.getState())
}
render() {
return (
<div>
<div>Num: {store.getState().num}</div>
<button onClick={this.add}>+ 5</button>
</div>
)
}
}
const render = () => {
ReactDOM.render(<App />, document.getElementById('root'))
}
store.subscribe(render)
render()
</script>
</body>
</html>