【问题标题】:Handling missing keys in Flags gracefully in Elm在 Elm 中优雅地处理 Flags 中丢失的键
【发布时间】:2018-03-19 05:45:52
【问题描述】:

我的应用通过标志从本地存储中获取初始化模型值。我向模型添加了一个新键,它在启动 Elm 应用程序时导致错误,因为通过标志传递的值中缺少键(“bar”)。考虑到将来可以添加更多的新键,并且我不想每次发生时都必须清除本地存储,有没有办法告诉 Elm 在标志中缺少键时分配默认值?

type alias Model =
    { foo : String, bar : Int }

update : msg -> Model -> ( Model, Cmd msg )
update _ model =
    model ! []

view : Model -> Html msg
view model =
    text <| toString model

main : Program Flags Model msg
main =
    Html.programWithFlags
        { init = init
        , update = update
        , view = view
        , subscriptions = always Sub.none
        }

HTML 代码

<body>
  <script>
    var app = Elm.Main.fullscreen({foo: "abc"})
  </script>
</body>

【问题讨论】:

    标签: elm flags decoder


    【解决方案1】:

    这是 Elm Slack 频道的 @ilias 友好提供的一个很好的解决方案。

    https://ellie-app.com/mWrNyQWYBa1/0

    module Main exposing (main)
    
    import Html exposing (Html, text)
    import Json.Decode as Decode exposing (Decoder)
    import Json.Decode.Extra as Decode  --"elm-community/json-extra"
    
    
    type alias Model =
        { foo : String, bar : Int }
    
    
    flagsDecoder : Decoder Model
    flagsDecoder =
        Decode.map2 Model
            (Decode.field "foo" Decode.string |> Decode.withDefault "hello")
            (Decode.field "bar" Decode.int |> Decode.withDefault 12)
    
    
    init : Decode.Value -> ( Model, Cmd msg )
    init flags =
        case Decode.decodeValue flagsDecoder flags of
            Err _ ->
                Debug.crash "gracefully handle complete failure"
    
            Ok model ->
                ( model, Cmd.none )
    
    
    update : msg -> Model -> ( Model, Cmd msg )
    update _ model =
        model ! []
    
    
    view : Model -> Html msg
    view model =
        text <| toString model
    
    
    main : Program Decode.Value Model msg
    main =
        Html.programWithFlags
            { init = init
            , update = update
            , view = view
            , subscriptions = always Sub.none
            }
    

    HTML

    <body>
      <script>
        var app = Elm.Main.fullscreen({foo: "abc"})
      </script>
    </body>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      • 2011-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多