简体   繁体   中英

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. 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. 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.

Any thoughts?

I think problem is caused by ObservableObject. It needs to store it's state. I think it's better to use StateObject. Please try that one for 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)")
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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