swiftUI:在 onAppear 中更改 @State 崩溃

mic*_*ica 5 swift swiftui

如果通过调用服务出现视图,我想设置一个@State 变量。
调用服务会onAppear导致应用程序崩溃。
在按钮操作中调用服务工作正常。

struct ContentView: View {
  @State var dirContent : [String] = []

  var body: some View {
    VStack {
      List {
        ForEach(dirContent, id: \.self){
          fileName in
          Text(fileName)
        }
      }
      Button("Get Data"){self.dirContent = Service.getData()}
    }
    .onAppear{
    //self.dirContent = Service.getData2()   // Crashes!!
    }
  }
}

class Service{
  static func getData()->[String]{
    // ... get Data from somewhere
    return ["line1", "line2"]
  }

  static func getData2()->[String]{
    // ... get Data from somewhere
    return ["line4", "line5"]
  }
}
Run Code Online (Sandbox Code Playgroud)

怎么了?

use*_*734 6

了解为什么会发生这种情况,请尝试修改您的代码

    var body: some View {
        VStack {
            List {
                ForEach(dirContent, id: \.self){
                    fileName in
                    Text(fileName).onAppear {
                        print("item appear")
                    }
                }
            }.onAppear {
                print("list appear")
            }
            Button("Get Data"){self.dirContent = Service.getData()}
        }
        .onAppear{
            print("content appear")
            DispatchQueue.main.async {
                self.dirContent = Service.getData2()
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

“老派”调试打印向我们展示了

content appear
list appear
item appear
item appear
Run Code Online (Sandbox Code Playgroud)

现在很清楚了,不是吗?