gpt4 book ai didi

elm - 在 Elm 中优雅地处理 Flags 中丢失的键

转载 作者:行者123 更新时间:2023-12-01 22:15:06 26 4
gpt4 key购买 nike

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

关于elm - 在 Elm 中优雅地处理 Flags 中丢失的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46622342/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com