You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NavigationLink与.navigationDestination使用错误致EventList导航异常

问题解决:EventList导航重复视图问题

问题原因

你的代码里把navigationDestination(for: EventItem.self)嵌套在了"Go To Events"这个NavigationLink的目标视图内部。在SwiftUI的NavigationStack中,导航目的地需要在导航栈的上下文里提前注册,如果放在子视图里,只有当该子视图(EventList)被加载后,目的地才会被注册。这就导致点击列表项的导航链接时,导航栈找不到对应的目的地,先重复push了一次EventList视图,之后目的地才生效,再导航到详情页,所以出现了“点击后先看到重复的EventList,返回才显示详情”的问题。

修复步骤

  1. 将.navigationDestination(for: EventItem.self)从NavigationLink的目标视图中移出,放到NavigationStack的直接子视图层级下(比如和ScrollView同级)。
  2. (可选)把EventList提取成独立的子视图,让代码结构更清晰。

修改后的代码

struct MainView: View {
    @State private var services = [Service]()
    @State private var media = [Media]()
    @State var event: [Event] = []
    var dataService = DataService()
    
    var body: some View {
        NavigationStack {
            ScrollView (showsIndicators: false)  {
                VStack {
                    ForEach(services) { p in
                        NavigationLink{ Level2View(service: p) } label:
                        {
                            MainCard(service: p)
                        }
                    }
                    
                    ForEach(media) { p in
                        NavigationLink{ Platform2View(media: p) } label: {
                            Platform1Card(media: p)
                        }
                    }
                    
                    NavigationLink("Go To Events"){
                        EventListView(event: event) // 提取成独立子视图,更清晰
                    }
                }
            }
            .onAppear {
                services = dataService.getServiceFileData()
                media = dataService.getPlatformData()
                event = dataService.getEventData()
            }
            // 把导航目的地移到根导航栈的层级下
            .navigationDestination(for: EventItem.self) { x in
                EventDetail(eventItem: x)
            }
        }
    }
}

// 提取EventList为独立子视图
struct EventListView: View {
    let event: [Event]
    
    var body: some View {
        List{
            ForEach(event) { p in
                Section(header: Text(p.sectionTitle)
                    .font(.title)
                    .fontWeight(.bold)
                ){
                    ForEach(p.eventItem) { x in
                        NavigationLink(value: x) {
                            EventRow(eventItem: x)
                        }
                    }
                }
            }
        }
        .navigationTitle("Events")
    }
}

为什么这样有效

把navigationDestination放在根NavigationStack的子视图上,确保在进入EventList之前,导航栈已经注册好了EventItem对应的目的地。当你点击列表项的NavigationLink(value: x)时,导航栈能直接找到EventDetail视图并跳转,不会再出现重复的EventList。

内容的提问来源于stack exchange,提问作者AnnLee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 08:42:34