1

使用包装器允许我们将 EnvironmentObject 向下传递到 ObservedObject。不错的方法..

但是,如果您想在 ViewObject 中操作 userData 而不是每次都创建一个全新的 ViewObject 怎么办?

在我的应用程序中,我更改 EnvironmentObject 后重新创建了整个视图,但我不知道如何避免这种情况。

struct MyCoolView: View {
    @EnvironmentObject var userData: UserData

    var body: some View {
        MyCoolInternalView(ViewObject(id: self.userData.UID))
    }
}

struct MyCoolInternalView: View {
    @EnvironmentObject var userData: UserData
    @ObservedObject var viewObject: ViewObject

    init(_ viewObject: ViewObject) {
        self.viewObject = viewObject
    }

    var body: some View {
            Text("\(self.viewObject.myCoolProperty)")
    }
}
4

1 回答 1

2

但是,如果您想在 ViewObject 中操作 userData 而不是每次都创建一个全新的 ViewObject 怎么办?

这是一个可能的解决方案的演示 - 将 viewObject 设置为StateObject(这将通过视图刷新使其持久化)并注入userData其中

使用 Xcode 12.1 / iOS 14.1 测试

class UserData: ObservableObject {
    @Published var UID = "1"
}

class ViewObject: ObservableObject {
    var userData: UserData?
    @Published var myCoolProperty = "Hello"
}

struct MyCoolView: View {
    @EnvironmentObject var userData: UserData

    var body: some View {
        MyCoolInternalView(self.userData)
    }
}

struct MyCoolInternalView: View {
    @StateObject private var viewObject = ViewObject()

    init(_ userData: UserData) {
        self.viewObject.userData = userData
    }

    var body: some View {
            Text("\(self.viewObject.myCoolProperty)")
    }
}
于 2020-12-05T16:25:35.167 回答