从列表中找到一个项目

时间:2018-01-07 17:35:51

标签: elm

榆树新手.. 我想从列表中获取一个项目。

这是模特(在第一篇文章中忘了) 我假设Report.id必须是Int !! ??

-- MODEL


type alias Model =
    { reports : List Report
    , alertMessage : Maybe String
    }


type alias Report =
    { id : Int
    , city : String
    , country : String
    }


initialModel : Model
initialModel =
    { reports = []
    , alertMessage = Nothing
    }


-- UPDATE


type Msg
= NewReports (Result Http.Error (List Report))
  | ShowReport
  | CloseAlert

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
    NewReports (Ok weatherReports) ->
        ( { model | reports = weatherReports }, Cmd.none )

    NewReports (Err error) ->
        ( { model | alertMessage = Just (httpErrorToMessage error) }, Cmd.none )

    CloseAlert ->
        ( { model | alertMessage = Nothing }, Cmd.none )

    ShowReport model ->
        ( ??? )

--VIEW now more complete to get the right picture

viewReportRow : Report -> Html Msg
viewReportRow report =
    tr []
        [ td [] [ text report.city ]
        , td [] [ text report.country ]
        , td [] []
            [ button
             [ class "button primary small"
             , onClick (ShowReport report.id)
             ]
             [ text "Show"]
             ]
        ]

如何以正确的方式从按钮发送ID并过滤具有此ID的条目的列表。

感谢您的支持

1 个答案:

答案 0 :(得分:2)

你走了 我已经更新了ShowReport消息以获取一个id(我假设它是一个String),显示了如何进行过滤(由您决定如何处理生成的列表),以及将您的视图片段转换为可以映射到model.reports

的函数

这仅表示您未提供模型的详细信息

type Msg
    = NewReports (Result Http.Error (List Report))
      | ShowReport String
      | CloseAlert

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
    NewReports (Ok weatherReports) ->
        ( { model | reports = weatherReports }, Cmd.none )

    NewReports (Err error) ->
        ( { model | alertMessage = Just (httpErrorToMessage error) }, Cmd.none )

    CloseAlert ->
        ( { model | alertMessage = Nothing }, Cmd.none )

    ShowReport id ->
        let report = 
            List.filter (\rep -> rep.id == id) model.reports
        in 
        (model, Cmd.none)

--VIEW

mkShowItem id =
    td []
        [
        button
        [ class "button small"
        , onClick (ShowReport id)
        ]
        [ text "Show"]
        ]