我想加载健康数据,以便在点击选项卡时显示一次用户步骤。但是通过使用 onAppear,每次点击选项卡时,它都会再次加载步骤并显示两次。我相信这是由于onAppear。这里应该使用什么替代方案?
struct StepPreview: View {
var body: some View {
NavigationView {
ScrollView {
LazyVStack{
ForEach(steps, id: \.id) { step in
VStack(spacing: 15){
Text("\(step.count)")
.font(.custom(customFont, size: 100))
.fontWeight(.semibold)
.multilineTextAlignment(.center)
.opacity(5)
.aspectRatio(contentMode: .fill)
.frame(width: 200, height: 200)
.padding(.bottom, -45)
}
}
}
.onAppear {
if let healthStore = healthStore {
healthStore.requestAuthorization { success in
if success {
healthStore.calculateSteps { statisticsCollection in
if let statisticsCollection = statisticsCollection {
// update the UI
updateUIFromStatistics(statisticsCollection)
}
}
}
}
}
}
}
}