小编典典
您想要实现一个存储状态的对象,可以使用回调函数对其进行修改。然后,您可以将这些函数传递给React组件。
例如,您可以创建一个商店:
function Store(initialState = {}) {
this.state = initialState;
}
Store.prototype.mergeState = function(partialState) {
Object.assign(this.state, partialState);
};
var myStore = new Store();
ReactDOM.render(
,
firstElement
);
ReactDOM.render(
,
secondElement
);
现在,FirstComponent和SecondComponent实例都可以调用this.props.mergeState({ . .
.})以将状态分配给同一存储。
我Store.prototype.getState作为练习留给读者。
请注意,您始终可以将store(myStore)本身传递给组件;这样做反而会减少反应。
以下是一些您可能会感兴趣的文档:
要在没有父子关系的两个组件之间进行通信,可以设置自己的全局事件系统。订阅componentDidMount()中的事件,取消订阅componentWillUnmount()中的事件,并在收到事件时调用setState()。助焊剂模式是解决此问题的一种可能方法。
2020-07-22