简体   繁体   English

SwiftUI 4 NavigationLink 正在调用链接两次

[英]SwiftUI 4 NavigationLink is invoking the link twice

I'm using the new NavigationLink in iOS 16 and hitting a problem where the target of the .navigationDestination is being called twice.我在 iOS 16 中使用新的NavigationLink并遇到了.navigationDestination的目标被调用两次的问题。 Example code:示例代码:

struct Content: View {
    var body: some View {
        NavigationStack {
            ScrollView {
                VStack {
                    ForEach(0..<10) { number in
                        NavigationLink(value: number) {
                            Text("\(number)")
                        }
                    }
                }
            }.navigationDestination(for: Int.self) { value in
                SubView(model: Model(value: value))
            }
        }
    }
}

class Model: ObservableObject {
    @Published var value: Int
                
    init(value: Int) {
        print("Init for value \(value)")
        self.value = value
    }
}

struct SubView: View {
    @ObservedObject var model: Model
    
    var body: some View {
        Text("\(model.value)")
    }
}

When I touch one of the numbers in the Content view the init message in the model is shown twice, indicating that the class has been instantiated more than once.当我在Content视图中触摸其中一个数字时,model 中的init消息会显示两次,表明 class 已被多次实例化。 This is not a problem in a trivial example like this, but in my app the model does a network fetch and calculation so this is being done twice, which is more of an issue.在像这样的简单示例中这不是问题,但在我的应用程序中,model 会进行网络获取和计算,因此需要执行两次,这更成问题。

Any thoughts?有什么想法吗?

I think problem is caused by ObservableObject.我认为问题是由 ObservableObject 引起的。 It needs to store it's state.它需要存储它的 state。 I think it's better to use StateObject.我认为最好使用StateObject。 Please try that one for SubView.请为 SubView 尝试那个。 :) :)

struct SubView: View {
@StateObject private var model: Model

init(value: Int) {
    self._model = StateObject(wrappedValue: Model(value: value))
}

var body: some View {
    Text("\(model.value)")
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM