【问题标题】:Why does onAppear() execute twice when placed on elements inside a NavigationView in swiftUI? (Xcode 12.0)为什么 onAppear() 在 swiftUI 中放置在 NavigationView 内的元素上时会执行两次? (Xcode 12.0)
【发布时间】:2020-10-28 11:32:08
【问题描述】:

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 中运行上面的代码会在选择 NavigationLink 时产生以下输出:

FirstView Appeared
FirstView Appeared
SecondView Appeared

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

如果是这样,在创建 firstview 并返回到 firstview 时加载一些数据的最佳做法是什么(因为 onAppear() 会在离开 firstView 时尝试加载一些数据)

【问题讨论】:

标签: navigation swiftui-navigationlink swiftui xcode12


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-08-01
    • 2021-03-28
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    • 2020-11-24
    • 2020-02-14
    相关资源
    最近更新 更多