2016-09-21 33 views
2

我想榆樹教程適應自己的小項目,我運行到與我供應Json.Decoder麻煩。Task.perform期待的第三個參數是不同類型的

我的代碼如下所示:

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) 

模型僅僅是一個有兩個領域,authorcontent記錄。

我得到的錯誤信息是這樣的:

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

可能相關:http://stackoverflow.com/questions/39320948/decode-json-array-with-objects-in-elm –

回答

2

我想我找到了我的問題。

我定義的消息沒有正確的類型。 FetchSucceed消息應該接受(List Comment.Model)而不是String。這意味着函數的參數需要反映並且模型將以不同的方式更新。

事情是這樣的:

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)