SwiftUI @AppStorage 不会在函数中刷新

问题描述

我试图在每个 .onAppear 重新加载数据,但是如果我在 SettingsView 中更改 @AppStorage nearMeter 的值,它不会更新 reloadNearStops 函数中的值并使用以前的 @AppStorage 值。

    struct SettingsView: View {
        @AppStorage(“nearMeter”) var nearMeter: Int = 1
        @State var meters = ["100 m","200 m","400 m","500 m","750 m","1 km"]
    
    var body: some View {


    ………
    
                            Picker(selection: $nearMeter,label: HStack {
                                    Text(NSLocalizedString(“near_stops_distance”,comment: ""))
                            }) {
                                ForEach(0 ..< meters.count,id: \.self) {
                                        Text(meters[$0])
                                }
                            }}}



    struct FavouritesView: View {
 @AppStorage(“nearMeter”) var nearMeter: Int = 1
        
            func reloadNearStops(nearMeter: Int) {
                
                print(nearMeter)
                readNearStopsTiMetable.fetchTiMetable(nearMeter:        getLonLatSpan(nearMeter: nearMeter),lat: (locationManager.lastLocation?.coordinate.latitude)!,lon: (locationManager.lastLocation?.coordinate.longitude)!)
            }
            
            
            func getLonLatSpan(nearMeter: Int) -> Double {
                let meters = [100,200,400,500,750,1000]
                
                if nearMeter < meters.count {
                    return Double(meters[nearMeter]) * 0.00001
                }
                else {
                    return 0.001
                }
            }
        var body: some View {
    
      
    .....
        
        ……….
        .onAppear() {
                    
                    if locationManager.lastLocation?.coordinate.longitude != nil {
                            if hasInternetConnection {
                                reloadNearStops(nearMeter: nearMeter)
                            }
                    }
        
        }}

解决方法

npm install react-router-dom --save 不会调用函数,但 AppStorage 可以在 onChange 更改时调用函数。

AppStorage