FirstView Appeared
打印两次。在第一次加载视图时一次,在选择NavigationLink时再次加载。
import SwiftUI
struct FirstView: View {
var body: some View {
NavigationView{
ZStack{
Text("FirstView").onAppear(perform: {print("FirstView Appeared")})
NavigationLink(destination: SecondView()) {
Text("Goto SecondView")
}.offset(y: 50)
}
}
}
}
struct SecondView: View {
var body: some View {
Text("SecondView").onAppear(perform: {print("SecondView Appeared")})
}
}
在选择了NavigationLink的情况下,在模拟器和个人设备上同时在Xcode 12.0 beta中运行上面的代码会产生以下输出:
FirstView Appeared
FirstView Appeared
SecondView Appeared
onAppear()预期行为的重复吗?
如果是这样,那么在创建firstview
并返回到firstview
时有什么最佳实践来加载一些数据(因为onAppear()会在离开{{ 1}})
答案 0 :(得分:0)
我知道我参加聚会有点晚了,但是如果其他任何人都遇到了同样的问题,只需将生命周期方法放在NavigationView
之外对我有用。我正在模拟器上测试-Xcode 12.2
struct fakeView1: View {
func didAppear() {
print("Appear")
}
func didDisappear() {
print("Disppear")
}
var body: some View {
NavigationView {
VStack {
Text("FAKE VIEW")
}
}
.onAppear { didAppear() }
.onDisappear { didDisappear() }
.navigationBarTitle("Fake View", displayMode: .inline)
}
}