首页 > 解决方案 > Swift:NavigationLink 多次调用目的地的 init 方法

问题描述

我有两个类 SubmitPhoneView 和 VerifyPhoneView。

出于某种原因,我注意到每当我在 SubmitPhoneView 的文本字段中输入一个数字时,它都会调用 VerifyPhoneView 的 init 方法。我希望它只被调用一次(当我按下 SubmitPhoneView 上的继续按钮时)

为什么会这样?

类 SubmitPhoneView:

import SwiftUI
import Firebase

struct SubmitPhoneView: View {

    @State private var phoneNumber: String = ""
    @State private var verificationID : String = ""
    @State private var presentMe = false

    var body: some View {

        ZStack {

            Text("My number is")

            HStack(spacing: 20){
                Text("+1")

                TextField("Enter phone number", text: $phoneNumber)
                    .keyboardType(.numberPad)
            }

            VStack {

                NavigationLink(destination: VerifyPhoneView(phoneNumber: $phoneNumber.wrappedValue, verificationID: $verificationID.wrappedValue), isActive: $presentMe) { EmptyView() }

                Button(action: {
                    self.submitPhoneNumber()
                    self.presentMe = true
                }) {
                    Text("Continue")
            }
        }
    }

    func submitPhoneNumber() {
        PhoneAuthProvider.provider().verifyPhoneNumber("+1" + phoneNumber, uiDelegate: nil) { (verificationID, error) in
            if error != nil {
                print(error.debugDescription)
                return
            }
            else {
                self.verificationID = verificationID!
            }
        }
    }

}

类验证电话视图:

import SwiftUI
import Firebase

struct VerifyPhoneView: View {

    private var phoneNumber: String
    @State private var verificationID: String
    @State private var verificationCode: String = ""
    @State private var loginSuccesful: Bool = false
    @EnvironmentObject var ls: LoginStatus
    @EnvironmentObject var currentUser: CurrentUser

    init(phoneNumber: String, verificationID: String) {
        print("the init method was called for VerifyPhoneView")
        self.phoneNumber = phoneNumber
       _verificationID = State(initialValue: verificationID)
        print(self.verificationID)
    }

    var body: some View {

        ZStack {

            Text("My code is")

            TextField("Enter code", text: $verificationCode)

            Button(action: {
                self.submitVerificationCode()
            }) {
                Text("Continue")
            }

        }

    }

    func submitPhoneNumber() {
       // doesn't matter
    }

    func submitVerificationCode() {
       // doesn't matter
    }

    }    

}

标签: swiftui

解决方案


使用DeferView,如下

VStack {

    NavigationLink(destination: DeferView {
       VerifyPhoneView(phoneNumber: $phoneNumber.wrappedValue, verificationID: $verificationID.wrappedValue) 
    }, isActive: $presentMe) { EmptyView() }

    Button(action: {
        self.submitPhoneNumber()
        self.presentMe = true
    }) {
        Text("Continue")
}

推荐阅读