list - SwifUI onAppear 被调用两次
问题描述
Q1:为什么 onAppears 会被调用两次?
Q2:或者,我可以在哪里拨打网络电话?
我在代码中的几个不同位置放置了 onAppears,它们都被调用了两次。最终,我试图在显示下一个视图之前进行网络调用,所以如果你知道不使用 onAppear 的方法,我会全神贯注。
我还尝试在我的列表中放置和删除 ForEach 并且它不会改变任何东西。
Xcode 12 Beta 3 -> Target iOs 14 CoreData 已启用但尚未使用
struct ChannelListView: View {
@EnvironmentObject var channelStore: ChannelStore
@State private var searchText = ""
@ObservedObject private var networking = Networking()
var body: some View {
NavigationView {
VStack {
SearchBar(text: $searchText)
.padding(.top, 20)
List() {
ForEach(channelStore.allChannels) { channel in
NavigationLink(destination: VideoListView(channel: channel)
.onAppear(perform: {
print("PREVIOUS VIEW ON APPEAR")
})) {
ChannelRowView(channel: channel)
}
}
.listStyle(GroupedListStyle())
}
.navigationTitle("Channels")
}
}
}
}
struct VideoListView: View {
@EnvironmentObject var videoStore: VideoStore
@EnvironmentObject var channelStore: ChannelStore
@ObservedObject private var networking = Networking()
var channel: Channel
var body: some View {
List(videoStore.allVideos) { video in
VideoRowView(video: video)
}
.onAppear(perform: {
print("LIST ON APPEAR")
})
.navigationTitle("Videos")
.navigationBarItems(trailing: Button(action: {
networking.getTopVideos(channelID: channel.channelId) { (videos) in
var videoIdArray = [String]()
videoStore.allVideos = videos
for video in videoStore.allVideos {
videoIdArray.append(video.videoID)
}
for (index, var video) in videoStore.allVideos.enumerated() {
networking.getViewCount(videoID: videoIdArray[index]) { (viewCount) in
video.viewCount = viewCount
videoStore.allVideos[index] = video
networking.setVideoThumbnail(video: video) { (image) in
video.thumbnailImage = image
videoStore.allVideos[index] = video
}
}
}
}
}) {
Text("Button")
})
.onAppear(perform: {
print("BOTTOM ON APPEAR")
})
}
}
解决方案
我有同样的问题。
我所做的是以下内容:
struct ContentView: View {
@State var didAppear = false
@State var appearCount = 0
var body: some View {
Text("Appeared Count: \(appearrCount)"
.onAppear(perform: onLoad)
}
func onLoad() {
if !didAppear {
appearCount += 1
//This is where I loaded my coreData information into normal arrays
}
didAppear = true
}
}
这通过确保只有 onLoad() 的 if 条件内部的内容才会运行一次来解决这个问题。
更新:Apple 开发者论坛上的某个人已经提交了一张票,Apple 已经意识到了这个问题。在 Apple 解决问题之前,我的解决方案是临时破解。
推荐阅读
- r - 如何使用列表列 dbplyr 进行分组和汇总
- java - 如何解决错误检测到未知的 BSON 类型
- sql - 如何将两条唯一记录相加并显示为一条新记录——OracleSQL?
- database - 为什么在 Next.js 中缓存 MongoDB 连接?它有效吗?
- invariants - Daikon 无法运行:“文件 example.dtrace 中的第 1 行出错:没有为程序点 program.point:::POINT 提供声明”
- python - 有没有办法在 Python 的输入中输出数组?
- reactjs - 为什么我使用“@brainhubeu/react-carousel”出现渲染问题:“^2.0.4
- json - Delphi Rest.JSON 不适用于简单类
- r - 如何在 TWFE 中添加多个虚拟变量?
- pine-script - PINESCRIPT - 锁定 ATR 用于止损和获利