swift - 在预览时增加函数中的变量会产生错误(swiftui)
问题描述
我有这段代码,我在其中调用返回视图的“makeView”函数,在makeView函数中,我递增变量“id”并将其传递给视图,但是当我这样做时,它会显示此错误
“从 SongBook.app (2935) 中的 SongsList_Previews 更新预览耗时超过 5 秒。”
令人惊讶的是,当我注释掉“self.id += 1”行时,一切正常。我是 SwiftUI 的新手,如果我遗漏了一些信息,请原谅我。
struct SongsList: View {
@State private var id: Int = 0
var body: some View {
VStack{
NavigationView {
List(songs) {
song in NavigationLink(
destination: SongMainView(song: song)) {
makeView(song: song)
}
}
}
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .leading)
.background(Color.orange.opacity(0.2))
.edgesIgnoringSafeArea(.all)
}
func makeView(song: Song) -> SongsIndexView {
self.id += 1;
return SongsIndexView(song: song, id: self.id)
}
}
解决方案
该变量用@State
属性包装器标记。
@State private var id: Int = 0
每次此值更改时,SwiftUI 都会尝试更新视图。
func makeView(song: Song) -> SongsIndexView {
self.id += 1;
return SongsIndexView(song: song, id: self.id)
}
这会导致无限循环,例如 -
id = 1
, updateView (但现在id = 2
因为id += 1
)id = 2
, updateView (但现在id = 3
因为id += 1
)
在更新视图时,您永远不应该改变状态。
推荐阅读
- php - 如何在将数据发送到 django API 视图时验证 wordpress wp_remote_post()
- angular - 如何获取 HTML 元素的 DropListRef?
- javascript - 如何重置下拉列表的值,单击 Vuejs 中的标签?
- mongodb - 如何从嵌套数组中获取不同的值?
- typescript - TypeScript 中重载函数的类型约束
- javascript - 使用一个点 wkt 作为一个带有 openlayers 的圆
- c# - .NET StringBuilder 中出现意外的 NullReferenceException
- node.js - TypeError:foundUser 不可迭代
- laravel - 当我想更新现有数据时,在 laravel 中找不到列
- azure-devops - 如何在多阶段 YAML 管道中添加部署后批准?