由于 NavigationLink,SwiftUI onAppear 被多次调用 [英] SwiftUI onAppear called multiple times because of NavigationLink
问题描述
SwiftUI onAppear 在导航链接中被多次调用.在我提供的示例中,它被调用了 5 次.这也会触发它的 StateObject 初始值设定项也被调用 5 次.如果您将导航链接注释掉,它会按预期执行.
SwiftUI onAppear gets called multiple times when inside of a navigation link. In the example I have provided, it gets called 5 times. This also triggers its StateObject initializer to get called 5 times as well. If you comment the Navigation Link out, it performs as expected.
这已经在 Xcode 12 GM 和 Xcode 12.2 以及 iOS 14 GM 和 iOS 14.2 beta 1 上进行了测试.也作为反馈 FB8721761 提交.
This has been tested with both Xcode 12 GM and Xcode 12.2 with iOS 14 GM and iOS 14.2 beta 1. Also filed as feedback 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})
}
}
推荐答案
我向 Apple 提交了反馈,此问题已在 iOS 14.2 beta 3 中得到解决.
I filed a feedback with Apple and this has been resolved in iOS 14.2 beta 3.
这篇关于由于 NavigationLink,SwiftUI onAppear 被多次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!