由于NavigationLink,多次调用SwiftUI onAppear

时间:2020-09-21 02:38:05

标签: swiftui

在导航链接内部,SwiftUI onAppear会被多次调用。在我提供的示例中,它被调用了5次。这也会触发其StateObject初始化程序也被调用5次。如果将导航链接注释掉,它将按预期执行。

这已在Xcode 12 GM和Xcode 12.2(在iOS 14 GM和iOS 14.2 beta 1上)进行了测试。也已作为反馈FB8721761归档。

struct ContentView: View {
    var body: some View {
        NavigationLink(destination: Color.red, label: {
            ImageView()
                .frame(width: 166.66, height: 250)
                .cornerRadius(10)
        })
    }
}

struct ImageView: View{
    @StateObject private var downloader = Downloaded(url: URL(string: "https://image.tmdb.org/t/p/w342/TnOeov4w0sTtV2gqICqIxVi74V.jpg")!)

    var body: some View{
        Rectangle()
            .onAppear{
                print("Appeared")
            }
    }
}

class Downloaded: ObservableObject{
    var cancellable: AnyCancellable?
    let url: URL

    init(url: URL){
        self.url = url
        download()
    }

    func download(){
        cancellable = URLSession.shared.dataTaskPublisher(for: url)
            .map(\.data)
            .receive(on: DispatchQueue.main)
            .eraseToAnyPublisher()
            .sink(receiveCompletion: { _ in
                print("Finished downloading")
            }, receiveValue: {_ in})
    }
}

1 个答案:

答案 0 :(得分:0)

我向Apple提交了反馈,并且在iOS 14.2 beta 3中已解决。