# NavigationStackの注意点 ## NavigationStackを使ったコード ```swift= struct RootView: View { var body: some View { NavigationStack { VStack(spacing: 16) { NavigationLink("green", value: Color.green) NavigationLink("gray", destination: ColorView(color: .gray)) } .frame(maxWidth: .infinity, maxHeight: .infinity) .navigationDestination(for: Color.self) { value in ColorView(color: value) } .navigationTitle(Text("White")) } } } struct ColorView: View { let color: Color var body: some View { VStack(spacing: 16) { NavigationLink("green", value: Color.green) .foregroundColor(.white) NavigationLink("gray", destination: ColorView(color: .gray)) .foregroundColor(.white) } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(color) .navigationTitle(Text(color.description)) } } struct Previews: PreviewProvider { static var previews: some View { RootView() } } ``` ## 挙動がおかしい? | 初期画面 | grayを押す | greenを押す | Stackがおかしい | | -------- | -------- | -------- | -------- | |![](https://hackmd.io/_uploads/B1w57S483.png)| ![](https://hackmd.io/_uploads/SJ8o7BVIh.png)|![](https://hackmd.io/_uploads/S1O2QBNL3.png) |![](https://hackmd.io/_uploads/SkBRXS4Un.png)| 本来white -> gray -> greenと画面遷移をしたはずがwhite -> green -> grayになってしまった。 ## 挙動検証 NavigationStackの挙動を検証するためにNavigationStackのpathがどう変化するかみてみる まずpathの変化を監視するために以下のコードを書く ```swift= class NavigationObject: ObservableObject { @Published var path: NavigationPath = .init() { didSet { print(path) } } } struct RootView: View { @StateObject var o = NavigationObject() var body: some View { NavigationStack(path: $o.path) { ... } } } ``` ### white -> grayの画面遷移時 結果: 何もprintされない。つまりpathは変化してない ### gray -> greenの画面遷移時 結果: `NavigationPath(_items: SwiftUI.NavigationPath.(unknown context at $106a682b8).Representation.eager([SwiftUI.(unknown context at $106a67ee8).ItemBox<SwiftUI.Color>]), subsequentItems: [], iterationIndex: 0)` pathが追加された ## まとめ NavigationStackを使ってもpathに追加される書き方とそうではない書き方がある。 | pathに追加される | pathに追加されない | | -------- | -------- | | NavigationLink(_ title,value:)|NavigationLink(_ title, destination:)| **これらを同じNavigationStack下で混ぜて書くとバグるの注意!**