Skip to content

依赖收集

AutoStore提供了一个collectDependencies的API,用于收集当前状态的依赖关系。通过该API,可以方便的查看当前状态的依赖关系,帮助开发者更好的理解状态之间的关系。

ts
const deps = store.collectDependencies(()=>{
    state.a=1
    state.b=1
    state.c
})

实际运行效果如下:

在 stackblitz 中打开
在 codesandbox 中打开
展开代码
复制代码
import React from "react"
import { createStore } from "@autostorejs/react"
import { Box } from "x-react-components"
import { useRef,useEffect } from "react"

const { state, collectDependencies } = createStore({
  a:1,
  b:2,
  c:3
})
 
export default ()=>{

  const ref = useRef<any>()

  useEffect(()=>{
    const deps = collectDependencies(()=>{
        state.a = 4  
        state.b = 5
        state.c      
    })
    deps.forEach(dep=>{
        ref.current.insertAdjacentHTML("beforeend",`<p style='margin:2px;'}>
        ${dep.join(".")} </p>`)
    })
  },[])

  return <Box ref={ref}/> 
} 
  • 该API只能收集同步操作的依赖关系。
  • 默认是将函数内部的all操作视为依赖。上例中我们对a,b进行了write操作,读取了c,所以a,b,c都会被收集到依赖中。
  • 通过options可以配置只收集read操作,或者只收集write操作。
ts
const deps = store.collectDependencies(()=>{
    state.a=1
    state.b=1
    state.c
},{operates:"read"})