gpt4 book ai didi

swiftUI:在 onAppear 中更改 @State 崩溃

转载 作者:行者123 更新时间:2023-12-03 21:59:12 24 4
gpt4 key购买 nike

如果通过调用服务出现 View ,我想设置一个@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"]
}
}

怎么了?

最佳答案

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

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

“老派”调试打印向我们展示了
content appear
list appear
item appear
item appear

现在很清楚了,不是吗?

关于swiftUI:在 onAppear 中更改 @State 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60662536/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com