导言
在 React 中,首推的是单向数据流以及单向数据绑定。
什么是单向数据流?VS. 双向数据流
什么是单向数据绑定? VS. 双向数据绑定
利用 Hooks 实现页面级响应式数据管理
// useReactiveData.ts
import { useMemo, useRef, useState } from 'react';
export function useReactiveData<T = any>(ininialState: any) {
const [, setRefresh] = useState({});
const innerDataRef = useRef(ininialState || {});
const dataProxy = useMemo(() => {
return new Proxy(ininialState || {}, {
set(target, prop, value) {
innerDataRef.current[prop] = value;
// console.log(target, prop, value, receiver);
setRefresh({});
return true;
},
get(target, prop) {
return innerDataRef.current[prop];
},
});
}, []);
return dataProxy;
}
使用Controller,拆分 UI 与 业务逻辑
// userController
import { useMemo, useRef, useState } from 'react';
type ControllerBaseOptions = {
changeHandler: () => void;
};
export class ControllerBase {
data: any;
changeHandler!: () => void;
$innerData: object = {};
// eslint-disable-next-line
__init(options: ControllerBaseOptions) {
this.$innerData = this.data || {};
this.changeHandler = options.changeHandler || function name() {};
const innerData = this.$innerData;
const { changeHandler } = this;
this.data = new Proxy(this.$innerData, {
set(target, prop, value) {
innerData[prop] = value;
changeHandler();
return true;
},
get(target, prop) {
return innerData[prop];
},
});
return this;
}
}
export function useController<T extends ControllerBase>(Ctrl: {
new (): { __init(options: ControllerBaseOptions): any };
}) {
const [, setRefresh] = useState({});
const ctrl = useMemo(() => {
// eslint-disable-next-line
return new Ctrl().__init({
changeHandler() {
setRefresh({});
},
});
}, []);
return ctrl;
}
用法
import { ControllerBase } from '@/hooks/userController';
// Logic
export class MarketingActivityController extends ControllerBase {
data = {
listLoading: false,
activityList: [],
};
queryActivityList = () => {
};
}
// UI
export default () => {
const ctrl = useController<MarketingActivityController>(MarketingActivityController);
useEffect(() => {
ctrl.queryActivityList();
}, []);
return <div>12345</div>
}