@antdp/antdp-ui
Version:
基于antd封装的组件
119 lines (118 loc) • 3.28 kB
JavaScript
import React from 'react';
import { setValue, getValue } from 'rc-field-form/lib/utils/valueUtil';
class Store {
constructor() {
// 保存状态
this.store = {};
//保存组件
this.componentLists = [];
// 初始化
this.init = entery => {
var {
initialValue
} = entery.props || {};
// 初始值
if (initialValue !== undefined) {
// 获取保存路径
var pathName = entery.getNamePath();
if (pathName) {
this.store = setValue(this.store, pathName, initialValue);
}
}
};
// 挂载之后 组件保存
this.register = entery => {
this.componentLists.push(entery);
var {
initialValue
} = entery.props || {};
if (initialValue !== undefined) {
entery.refresh();
}
return () => {
// 组件卸载进行组件删除
this.componentLists = this.componentLists.filter(item => item !== entery);
// 保存的值进行删除
var pathName = entery.getNamePath();
if (pathName) {
this.store = setValue(this.store, pathName, undefined);
}
};
};
// 获取值
this.getStoreState = pathName => {
if (pathName) {
// 如果有路径,则根据路径获取值
return getValue(this.store, pathName);
}
return this.store;
};
this.getComponents = () => {
return this.componentLists;
};
this.getStore = () => {
return {
getComponents: this.getComponents,
getStoreState: this.getStoreState,
getItemStore: this.getItemStore,
setInitialValues: this.setInitialValues,
updateValue: this.updateValue
};
};
// 子项内的方法
this.getItemStore = () => {
return {
init: this.init,
register: this.register,
getStoreState: this.getStoreState,
updateValue: this.updateValue,
getValue: this.getValue
};
};
this.setInitialValues = (initialValues, init) => {
if (init) {
this.store = Object.assign({}, this.store, initialValues);
}
};
// 更新值
this.updateValue = (pathName, value) => {
var path = Array.isArray(pathName) ? pathName : [pathName];
this.store = setValue(this.store, path, value);
// 通知对应的组件进行强制更新
this.notifyObservers(path);
};
// 获取值
this.getValue = pathName => {
var path = Array.isArray(pathName) ? pathName : [pathName];
return getValue(this.store, path);
};
// 通知更新组件
this.notifyObservers = pathName => {
this.componentLists.forEach(_ref => {
var {
refresh,
getNamePath
} = _ref;
var currentPath = getNamePath();
// 判断路径相同的进行值更新
if (currentPath.join('') === pathName.join('')) {
refresh();
}
});
};
}
}
/** 状态管理 */
var useStore = form => {
var formRef = React.useRef();
if (!formRef.current) {
if (form) {
formRef.current = form;
} else {
var formStore = new Store();
formRef.current = formStore.getStore();
}
}
return [formRef.current];
};
export default useStore;