我正在尝试将 Elm 教程改编为我自己的小项目,但我在使用我提供的 Json.Decoder 时遇到了麻烦。
我的代码如下所示:
type Msg
= RetrieveComments
| FetchSucceed String
| FetchFail Http.Error
update : Msg -> Model -> ( Model, Cmd Msg)
update msg model =
case msg of
RetrieveComments ->
(model, retrieveComments)
FetchSucceed whatever ->
(model, Cmd.none)
FetchFail error ->
(model, Cmd.none)
retrieveComments : Cmd Msg
retrieveComments =
let
url = "/ReactTutorial/comments.json"
in
Task.perform FetchFail FetchSucceed (Http.get commentsCollectionDecoder url)
commentsCollectionDecoder : Decode.Decoder (List Comment.Model)
commentsCollectionDecoder =
Decode.list commentDecoder
commentDecoder : Decode.Decoder Comment.Model
commentDecoder =
Decode.object2 Comment.Model
("author" := Decode.string)
("content" := Decode.string)
该模型只是一个包含两个字段的记录,author
and content
.
我收到的错误消息是这样的:
The 3rd argument to function `perform` is causing a mismatch.
44| Task.perform FetchFail FetchSucceed (Http.get commentsCollectionDecoder url)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Function `perform` is expecting the 3rd argument to be:
Task.Task Http.Error String
But it is:
Task.Task Http.Error (List Comment.Model)
我想我找到了我的问题。
我定义的消息没有正确的类型。这FetchSucceed
消息应该接受(List Comment.Model)
而不是一个String
。这意味着update
函数的参数需要反映,并且模型将以不同的方式更新。
像这样的事情:
type Msg
= RetrieveComments
| FetchSucceed (List Comment.Model)
| FetchFail Http.Error
update msg model =
case msg of
RetrieveComments ->
(model, retrieveComments)
FetchSucceed newComments ->
({ model | comments = newComments }, Cmd.none)
FetchFail error ->
(model, Cmd.none)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)