1

出于某种原因,onAppear 被调用了两次。我创建了一个测试项目并尝试添加另一个解决方案中编写的 ZStack,但它对我不起作用。在这种情况下可以做什么?

struct ContentView: View {
    let items = ["One","Two"]
    var body: some View {
        TabView {
            ForEach(self.items, id: \.hashValue) { (item) in
                TextView(text: item)
                    .tabItem { Text(item) }
                    .tag(item)
            }
        }
    }
}
struct TextView : View {
    let text: String
    @State private var params: String = ""
    var body: some View {
        ZStack {
            Text("\(self.text): \(self.params)")
        }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .onAppear {
                print(">>> \(self.text)")
                self.params = "onAppear"
            }
            .onDisappear {
                print("<<< \(self.text)")
                self.params = "onDisappear"
            }
    }
}

如果您切换一次到两次:

>>> One
>>> Two
<<< One
>>> One
4

0 回答 0