V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
SystemLight
V2EX  ›  React

React 中如何可以实现 vue3.2 新增的 effectScope 特性呢?

  •  
  •   SystemLight ·
    SystemLight · 2022-07-27 11:51:07 +08:00 · 2120 次点击
    这是一个创建于 611 天前的主题,其中的信息可能已经有所发展或是发生改变。

    effectScope 可以让不同的组件之间共享相同的依赖存活周期,即可以实现多个组件共享相同状态,并且实现所有的组件都被销毁后触发响应式状态销毁,这样优化了相同的内容重复注册,还共享了数据状态

    import {ref, onScopeDispose, effectScope} from 'vue';
    
    export function createSharedComposable(composable) {
        let subscribers = 0
        let state, scope
    
        const dispose = () => {
            if (scope && --subscribers <= 0) {
                scope.stop()
                state = scope = null
            }
        }
    
        return (...args) => {
            subscribers++
            if (!state) {
                scope = effectScope(true)
                state = scope.run(() => composable(...args))
            }
            onScopeDispose(dispose)
            return state
        }
    }
    
    export let useShareMouse = createSharedComposable(useMouse)
    
    export function useMouse() {
        const x = ref(0)
        const y = ref(0)
    
        function handler(e) {
            x.value = e.x
            y.value = e.y
        }
    
        window.addEventListener('mousemove', handler)
    
        onScopeDispose(() => {
            console.log('onUnmounted')
            window.removeEventListener('mousemove', handler)
        })
    
        return {x, y}
    }
    
    
    3 条回复    2022-07-27 13:28:24 +08:00
    SystemLight
        1
    SystemLight  
    OP
       2022-07-27 12:02:50 +08:00
    突然想到可以用高阶组件配合 context 可以实现,[code]( https://github.com/SystemLight/create-kiva/blob/master/packages/react-kiva/template/kiva/model/index.tsx),但是需要操作上层组件,但是 vue 中不需要操作上层组件就可以实现,根本问题可能是 react hook 无法存在分支,也不能主动触发内部声明周期
    mxT52CRuqR6o5
        2
    mxT52CRuqR6o5  
       2022-07-27 12:57:08 +08:00
    只要放弃官方的 hooks 就能在 react 中实现类似 effectScope 的东西(比如 mobx )
    serco
        3
    serco  
       2022-07-27 13:28:24 +08:00
    React 实现这种要方便的话基本都是靠生态里的工具,hook 只负责共享代码,加上 jotai 或者 recoil 就可以了。context 太麻烦了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5436 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 07:44 · PVG 15:44 · LAX 00:44 · JFK 03:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.