【问题标题】:Elm - Get JSON List DataElm - 获取 JSON 列表数据
【发布时间】:2023-03-19 06:33:01
【问题描述】:

我正在尝试从此 URL 获取 JSON 数据列表:https://raw.githubusercontent.com/raywenderlich/recipes/master/Recipes.json

我不明白在这种情况下该怎么办

...
main =
  App.program
  { init = init
  , view = view
  , update = update
  , subscriptions = \_ -> Sub.none
  }

-- MODEL

type alias Model =
  { name : String
  , imageURL: String
  }

init =
  (Model "" "", Cmd.none)

-- UPDATE

type Msg
  = Recipes
  | FetchSucceed (List Model)
  | FetchFail Http.Error

update msg model =
  case msg of
    Recipes ->
      (model, fetchRecipes)

    FetchSucceed recipe ->
      (recipe, Cmd.none)

    FetchFail _ ->
      (model, Cmd.none)


-- VIEW

view model =
  div []
    [ ul [] (List.map getItem model)
  ]


getItem item =
  li [] [ text item.name ]

-- HTTP

fetchRecipes =
  let
    url =
      "https://raw.githubusercontent.com/raywenderlich/recipes/master/Recipes.json"
  in
    Task.perform FetchFail FetchSucceed (Http.get decodeListRecipes url)


decodeRecipes =
  Json.object2 Model
    ("name" := Json.string)
    ("imageURL" := Json.string)

decodeListRecipes =
  Json.list decodeRecipes

但我不断收到此错误:

Function `program` is expecting the argument to be:
    { ...,
      update :
        Msg
          -> { imageURL : String, name : String }
          -> ( { imageURL : String, name : String }, Cmd Msg ) ,
        view : { imageURL : String, name : String } -> Html Msg
    }

But it is: 
   { ...
   , update : Msg -> List Model -> ( List Model, Cmd Msg )
   , view : List { a | name : String } -> Html b
   }

【问题讨论】:

    标签: elm


    【解决方案1】:

    您的 FetchSucceed 标记被定义为具有模型列表 (FetchSucceed (List Model)),但在您的 update 函数中,您将其视为单个模型而不是列表。如果我将值更改为复数,它应该强调问题区域:

    FetchSucceed recipes ->
        (recipes, Cmd.none)
    

    在不确切知道您要达到的目标的情况下,我只能提供一个潜在解决方案的提示,例如,如果您只想获取列表的第一个元素并在没有食谱的情况下回退到当前模型返回,您可以执行以下操作:

    FetchSucceed recipes ->
        let recipe =
            case List.head recipes of
                Just r -> r
                Nothing -> model
        in
            (recipe, Cmd.none)
    

    【讨论】:

    • 感谢 Chad 的帮助我后来发现我需要在“init”函数的列表中制作食谱
    猜你喜欢
    • 2012-01-29
    • 2018-11-30
    • 2019-01-15
    • 2018-11-29
    • 1970-01-01
    • 2020-11-17
    • 2012-09-18
    • 2016-10-24
    • 1970-01-01
    相关资源
    最近更新 更多