作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我来自 React,在那里我使用 useMemo
来确保某些计算不会过于频繁地执行。我如何在 SwiftUI 中做类似的事情?
考虑这个例子:
struct MyView: View {
var records: [Record]
var body: some View {
Text("expensive summary: \(self.expensiveSummary)")
}
var expensiveSummary: String {
// based on records, return string
// containing a summary of records
return ""
}
}
有什么方法可以确保我的 expensiveSummary
仅在我的记录数组更改时被调用?
最佳答案
我认为我们可以创建一个包装器 View 作为 Equatable
。(也许,我们可以使用 EquatableView
或 .equatable()
修饰符吗?)
struct UseMemo<KeyType: Equatable, ViewType: View>: View, Equatable {
let key: KeyType
let content: (KeyType) -> ViewType
var body: some View {
content(key)
}
static func ==(lhs: UseMemo, rhs: UseMemo) -> Bool {
return lhs.key == rhs.key
}
}
struct MyView: View {
@State var records: [Int] = (Array<Int>)(1...10000)
@State var other = false
var body: some View {
VStack {
Button("Update other", action: { self.other.toggle() })
Text("Other: \(String(other))") // This will be called everytime
Button("Update records", action: { self.records.append(1) })
UseMemo(key: records) { keys in
// This is not called even if updated "other"
// This is called when updates "records"
Text("expensive summary: \(expensiveSummary)")
}
// This will be called everytime
Text("expensive summary: \(expensiveSummary)")
}
}
var expensiveSummary: String {
String(records.randomElement()!)
}
}
以下内容对我有帮助。
关于swiftui - SwiftUI 中的记忆化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60893458/
为什么 Silverlight 中有这么多内存? 数据: 我有时在用户界面上有很多复选框和其他复选框。当然,我正在从视觉对象中删除复选框和其他控件,但 Silverlight 的内存使用量总是增加;它
我调用一个返回给定特定链式方法的数组的对象: Songs::duration('>', 2)->artist('Unknown')->genre('Metal')->stars(5)->getAllA
为了解释标题.. Selenium RC keeps insisting that A system shutdown has already been scheduled 并因此拒绝进行自动化测试。
我是一名优秀的程序员,十分优秀!