网络编程 发布日期:2025/11/6 浏览次数:1
"htmlcode">
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,
};
}
我们的 createStore 非常简单,算上空行也只有 33 行,总共暴露了 3 个方法,没有 Redux 里的 dispatch 和 reducer,直接通过 setState 方法改变状态。下面我们来用它一个计数器的例子。
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>
);
};
}
例子中 Buttons 里通过 store.setState 来改变 store 中的状态,并不会引起整个 Counter 的重新 render,但是因为 Result 中订阅了 store 的变化,所以当 count 有变化的时候就可以通过改变自己组件内的状态来重新 render,这样就巧妙地避免了不必须要的 render。
最后,上面的 createStore 虽然只有几十行代码,我还是把它写成了一个叫 mini-store 库放在 GitHub 上,并且提供了类似 Redux 的 Provider 和 connect 方法,总共加起来也就 100 多行代码。如果你也在写 React 组件库,需要管理一个复杂组件的状态,不妨试试这个优化方式。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。