reecho
Version:
Reecho 是一款基于依赖收集的MVVM框架,它具有以下特点 - 声明式数据: 基于proxy的依赖收集 - 使用函数定义组件,但组件不会如React一样重复执行造成心智负担 - 读写分离,读取状态和更改状态统一使用函数,避免vue3的ref一样有时需要`xxx.value`有时不需要的不一致性 - 使用TS编写,类型友好
50 lines (43 loc) • 1.09 kB
text/typescript
import { isObject } from "./../shared/index";
import { isFunction } from "src/shared";
import { ref } from "./ref";
interface FunctionSetState<T> {
(prev: T): T;
__isProduce: boolean | undefined;
}
export function useState<T>(
initState: T
): [() => T, (val: T | ((prev: T) => T)) => void] {
const state = ref(initState);
const getState = () => state.value;
function setState(valueOrFn: T | FunctionSetState<T>) {
if (isFunction(valueOrFn)) {
if (valueOrFn.__isProduce) {
// TODO
if (!isObject(state.value)) {
throw new Error("produce must be used in object state");
} else {
state.value = valueOrFn(state.value);
}
} else {
state.value = valueOrFn(state.value);
}
} else {
state.value = valueOrFn;
}
}
return [getState, setState];
}
export function produce<T>(fn: (state: T) => void): (prev: T) => T {
const retFn = (state: T) => {
fn(state);
return {...state};
};
retFn.__isProduce = true;
return retFn;
}
/*
setState(produce(s => {
s.a = 1
}))
*/