Elm中如何从Decoder Msg类型里提取Msg值?
Elm 0.18 从 Decoder Msg 提取 Msg 值的方法
在Elm里,Decoder Msg只是一份解析规则的描述,并不是实际的Msg值。要拿到具体的Msg,你得运行解码器,把目标JSON数据传进去解析。
常用的两种解析方式:
- 解析JSON字符串:用
Json.Decode.decodeString,它的类型签名是Decoder a -> String -> Result String a,会返回一个Result类型——成功时是Ok Msg,失败时是Err 错误信息。 - 解析
Json.Value类型数据:用Json.Decode.decodeValue,签名是Decoder a -> Json.Value -> Result String a,常见于处理端口传来的JSON值场景。
举个实际代码例子:
import Json.Decode as Decode -- 假设你已经实现好的Msg解码器 msgDecoder : Decoder Msg msgDecoder = Decode.oneOf [ Decode.map SelectElement (Decode.field "elementId" Decode.int) , Decode.map2 ApplyTool (Decode.maybe (Decode.field "toolId" Decode.int)) (Decode.map2 Mouse (Decode.field "x" Decode.int) (Decode.field "y" Decode.int)) ] -- 解析JSON字符串的示例 parseFromString : Result String Msg parseFromString = Decode.decodeString msgDecoder "{\"elementId\": 3}" -- 处理解析结果的逻辑 getMsgFromResult : Result String Msg -> Msg getMsgFromResult result = case result of Ok validMsg -> validMsg Err _ -> -- 解析失败时返回一个默认Msg,根据业务场景调整 SelectElement 0
需要注意的是,Elm是纯函数语言,你没法跳过错误处理直接“提取”Msg——必须显式处理Result的成功和失败分支。如果是在端口通信这类场景下,通常会在update函数里处理解析结果:
update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of ReceivePortJson jsonValue -> case Decode.decodeValue msgDecoder jsonValue of Ok actualMsg -> update actualMsg model Err err -> -- 这里可添加错误处理逻辑,比如打印日志或保持模型不变 (model, Cmd.none) -- 其他Msg分支处理...
内容的提问来源于stack exchange,提问作者Sondre Lindaas Gjesdal
相关产品推荐
相关产品推荐

