6

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")})
    }
}

在选择导航链接时,在模拟器和个人设备上同时在XCode 12.0 Beta中运行代码:

FirstView Appeared
FirstView Appeared
SecondView Appeared

这是 onAppear() 预期行为的重复吗?

如果是这样,有什么最佳实践可以在firstview创建时加载一些数据,然后在返回时firstview加载(因为 onAppear() 会在导航离开时尝试加载一些数据firstView

4

1 回答 1

5

我知道我参加聚会有点晚了,但如果其他人有同样的问题,只需将生命周期方法放在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)
    }
}
于 2020-11-27T17:50:54.373 回答