如何从 SwiftUI 中的 EnvironmentObject 加载状态?
所以我正在研究一个视图,我想从一个类似于数据库的环境对象加载状态。
我想实现这样的目标:
class MyDB: ObservableObject {
func getName(_ id: RecordID) -> String { ... }
func getChildren(_ id: RecordID) -> [RecordID] { ... }
var didUpdate: PassthroughSubject...
}
struct TreeView: View {
let id: RecordID
@EnvironmentObject var db: DB
@State var name: String
@State var children: [RecordID]
func loadState() {
self.name = db.getName(id)
self.children = db. getChildren(id)
}
var body: some View {
Text(self.name)
List(self.children) { child in
TreeView(id: child)
}
.onReceive(self.db.didUpdate) { _ in
self.loadState()
}
}
}
所以基本上我只想将树视图中节点的 id 传递给子视图,然后使用 loadState
从该环境对象加载状态显示视图之前的函数。
有什么办法可以实现这一点吗?例如,我是否可以实现某种生命周期函数,该函数将在环境绑定后调用?
或者例如我可以在自定义 init 中实现 loadState 吗?
处理这个问题的惯用方法是什么?
So I am working on a view where I want to load state from an EnvironmentObject which acts something like a database.
I would like to achieve something like this:
class MyDB: ObservableObject {
func getName(_ id: RecordID) -> String { ... }
func getChildren(_ id: RecordID) -> [RecordID] { ... }
var didUpdate: PassthroughSubject...
}
struct TreeView: View {
let id: RecordID
@EnvironmentObject var db: DB
@State var name: String
@State var children: [RecordID]
func loadState() {
self.name = db.getName(id)
self.children = db. getChildren(id)
}
var body: some View {
Text(self.name)
List(self.children) { child in
TreeView(id: child)
}
.onReceive(self.db.didUpdate) { _ in
self.loadState()
}
}
}
So basically I would like to just pass the id of the node in the tree view to the child view, and then load the state from this environment object with the loadState
function before the view is displayed.
Is there any way to achieve this? For instance, is there some kind of lifecycle function I could implement which will be called after the environment is bound?
Or for example can I implement loadState inside a custom init?
What would be the idiomatic way to handle this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在此处提供了解释如果你想查看一下。
您需要在父视图上使用
.environmentObject(myDBInstance)
传递MyDB
实例,以便所有子视图都可以通过@EnvironmentObject
从环境中读取代码>.I have provided an explanation here if you want to check it out.
You will need to pass your
MyDB
instance using.environmentObject(myDBInstance)
on a parent view, so all children views can read from the environment through@EnvironmentObject
.尝试使用不同的方法,例如下面的代码,
其中
children
和name
是MyDB
的已发布变量,并且这些函数只是将数据加载到其中。
Try using a different approach, such as the following code,
where
children
andname
are published var ofMyDB
, andthe functions just load the data into those.