依赖收集
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"})