SwiftUI 中当 NavigationView 嵌套在 TabView 中时,onAppear 为什么会被调用两次?

7
我有一个TabView,其中每个标签都嵌套在NavigationView中。每个标签第一次出现时,我会依次调用onAppear(),onDisappear(),onAppear()生命周期方法。看起来onAppear被调用了两次。这只发生在第一次。如果我导航回同一个标签,只有onAppear()被调用,并且只调用一次。
以下是最小示例:
struct Page1: View {
    init() { print("Page 1 init") }
    
    var body: some View {
        NavigationView {
            Text("Page 1")
                .onAppear(perform: { print("Page 1 appearing") })
                .onDisappear(perform: { print("Page 1 disappearing") })
        }
    }
}

struct Page2: View {
    init() { print("Page 2 init") }
    
    var body: some View {
        NavigationView {
            Text("Page 2")
                .onAppear(perform: { print("Page 2 appearing") })
                .onDisappear(perform: { print("Page 2 disappearing") })
        }
    }
}

struct ContentView: View {
    var body: some View {
        TabView {
            Page1().tabItem { Text("Page 1") }
            Page2().tabItem { Text("Page 2") }
        }
    }
}

这是打印出来的结果:

Page 1 init
Page 2 init
Page 1 appearing
Page 1 disappearing
Page 1 appearing

如果我点击第二个标签,会发生什么?

Page 1 init
Page 2 init
Page 1 appearing
Page 1 disappearing
Page 1 appearing
// here I clicked on second tab
Page 2 appearing
Page 2 disappearing
Page 2 appearing
Page 1 disappearing

我也遇到了同样的问题:onAppear方法被调用了多次。我不知道为什么会这样,但是我通过在视图中存储一个布尔值并在onAppear方法中添加条件来解决了这个问题。所以,如果需要onAppear方法,就加上if needOnAppear { needOnAppear = false }的判断条件。 - West1
1个回答

0
    TabView {
        NavigationView {
            VStack {
                Color.red
                    .onAppear {
                        print("appear : red")
                    }
                    .onDisappear {
                        print("disappear : red")
                    }
            }.onAppear {
                print("appear")
            }
        }
    }

在 iOS 15 beta 模拟器上进行测试

输出结果:

appear : red
appear
disappear : red
appear : red

2
你在tabview中只有一个选项卡。当你在两个选项卡之间切换时,问题就出现了。 - andrei

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接