function createStore(initialState) {
let state = initialState;
const listeners = [];
function setState(partial) {
state = {
...state,
...partial,
};
for (let i = 0; i < listeners.length; i++) {
listeners[i]();
}
}
function getState() {
return state;
}
function subscribe(listener) {
listeners.push(listener);
return function unsubscribe() {
const index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
}
return {
setState,
getState,
subscribe,
};
}
class Counter extends React.Component {
constructor(props) {
super(props);
// 初始化 store
this.store = createStore({
count: 0,
});
}
render() {
return (
<div>
<Buttons store={store} />
<Result store={store} />
</div>
)
}
}
class Buttons extends React.Component {
handleClick = (step) => () => {
const { store } = this.props;
const { count } = store.getState();
store.setState({ count: count + step });
}
render() {
return (
<div>
<button onClick={this.handleClick(1)}>+</button>
<button onClick={this.handleClick(1)}>-</button>
</div>
);
}
}
class Result extends React.Component {
constructor(props) {
super(props);
this.state = {
count: props.store.getState().count,
};
}
componentDidMount() {
this.props.store.subscribe(() => {
const { count } = this.props.store.getState();
if (count !== this.state.count) {
this.setState({ count });
}
});
}
render() {
return (
<div>{this.state.count}</div>
);
};
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有