Solidjs状态更新管理在React中的应用

Posted 前端海洋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Solidjs状态更新管理在React中的应用相关的知识,希望对你有一定的参考价值。

Solidjs状态更新

const context = [];
function subscribe(running, subscriptions) { subscriptions.add(running); running.dependencies.add(subscriptions);}
export function createSignal(value) { const subscriptions = new Set();
const read = () => { const running = context[context.length - 1]; if (running) subscribe(running, subscriptions); return value; };
const write = (nextValue) => { value = nextValue;
for (const sub of [...subscriptions]) { sub.execute(); } }; return [read, write];}

function cleanup(running) { for (const dep of running.dependencies) { dep.delete(running); } running.dependencies.clear();}
export function createEffect(fn) { const execute = () => { cleanup(running); context.push(running); try { fn(); } finally { context.pop(); } };
const running = { execute, dependencies: new Set() };
execute();}
export function createMemo(fn) { const [s, set] = createSignal(); createEffect(() => set(fn())); return s;}
添加一个批量更新的函数
function flush(fn) { if (typeof MessageChannel !== undefined) { const { port1, port2 } = new MessageChannel(); port1.onmessage = fn; port2.postMessage(null); } else { setTimeout(fn); }}
借用上述更新原理我们可以在 React中应用封装一个状态管理

export function createStore(initState) { const createSetter = {}; const stateKeys = Object.keys(initState); for (let i = 0; i < stateKeys.length; i++) { const [get, set] = createSignal(initState[stateKeys[i]]); createSetter[stateKeys[i]] = {get,set} }
const dispatch = (state) => { const dispatchKeys = Object.keys(state); dispatchKeys.forEach(item => createSetter[item].set(state[item])); }
const getStore = () => Object.keys(createSetter).reduce((pre,cur) => { pre[cur] = createSetter[cur].get(); return pre; }, {})
const useStore = (stateKeys) => { const [, forceUpdate] = useState({}); const updateRef = useRef(false); const queue = useRef(0); useEffect(() => { createEffect(() => { stateKeys.forEach(item => { createSetter[item].get() }); if (updateRef.current) { queue.current += 1; queue.current === 1 && flush(() => { queue.current = 0; forceUpdate({}); }) } else { updateRef.current = true; } }); }, []);
return getStore() }
return { useStore, getStore, dispatch };}
利用上述状态管理一个小

以上是关于Solidjs状态更新管理在React中的应用的主要内容,如果未能解决你的问题,请参考以下文章

SolidJS硬气的说:我比React还react

React - 每当更新反应上下文中的状态时如何调用函数?

React 中的 Redux 详解:

react监听仓库数据变化

如何知道所有 setState 更新是不是已应用于 React 组件中的状态?

2022 年,我们再来谈谈 React 状态管理