我正在尝试将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
和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)
答案 0 :(得分:2)
我想我弄明白了我的问题。
我定义的消息没有正确的类型。 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)