【问题标题】:Elm 0.17: Task.perform and MaybeElm 0.17:Task.perform 和 Maybe
【发布时间】:2016-06-16 00:10:36
【问题描述】:

我希望有人可以在 Task.perform 方面帮助我,因为我并不真正了解如何处理 Maybe 响应 - 文档并没有让我更清楚。

在我的model 我有results 其中Maybe 项目列表或Nothing

-- model

type alias Item =
  { name : String}

type alias Model =
  { results : Maybe (List Item) }

model = {
  results = Nothing
}

我执行一个任务并像这样解码它:

-- Task

fetch : String -> Cmd Msg
fetch query =
  let url =
    "https://some_url" ++ query
  in
    Task.perform FetchFail FetchSuccess (Http.get decode url)


-- decoder

decoder: Json.Decoder (List Item)
decoder =
  Json.at ["data"] (Json.list nestedListDecoder)


-- nestedListDecoder

nestedListDecoder : Json.Decoder Item
nestedListDecoder =
  Json.object1 Item
    ("name" := Json.string)

然后我在更新中处理响应:

-- update

type Msg
  = FetchSuccess (Maybe (List Item))
  | FetchFail Http.Error


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
  case msg of
    FetchSuccess results ->
      case results of
        Nothing ->
          ( { model | results = Nothing}, Cmd.none)
        Just res ->
          ( { model | results = res }, Cmd.none)

    FetchFail err ->
      -- ... handle error

并在视图中迎合Maybe:

-- view

result : Item -> Html Msg
result item =
  li [] [ text item.name ]


view : Model -> Html Msg
view model =
  ul [ ] (List.map result (Maybe.withDefault [] model.results))

在处理Maybe of results 时出现此错误。

198|     Task.perform FetchFail FetchSuccess (Http.get repos url)
                                              ^^^^^^^^^^^^^^^^^^
Function `perform` is expecting the 3rd argument to be:

    Task Http.Error (Maybe (List Repo))

But it is:

    Task Http.Error (List Repo)

谁能建议我还需要在哪里为Maybe 提供服务?

【问题讨论】:

    标签: elm


    【解决方案1】:

    对您的decoder 进行简单调整即可解决此问题。解码器只需要使用Json.Decode.maybe

    decoder: Json.Decoder (Maybe (List Item))
    decoder =
      Json.maybe <| Json.at ["data"] (Json.list nestedListDecoder)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      • 1970-01-01
      • 2016-10-27
      • 2017-01-30
      • 1970-01-01
      相关资源
      最近更新 更多