【问题标题】:How can the `Msg` type be separated into many types in Elm?`Msg` 类型如何在 Elm 中分成多种类型?
【发布时间】:2018-05-09 05:35:55
【问题描述】:

在 Elm 中使用 model 和 update 的标准方式是定义 Model 和 Msg 类型,以及 update 函数:

type alias Model = { ... }

type Msg = Msg1 | Msg2 | ...

update : Msg -> Model -> (Model, Cmd Msg)
...

随着应用程序的增长,所有这些类型和功能都会变得更加复杂。我想通过以下方式将它们分开:

type alias Model1 = { ... }
type alias Model2 = { ... }
type alias Model = { model1 : Model1, model2 : Model2 }

type Msg1 = Msg1a | Msg1b | ...
type Msg2 = Msg2a | Msg2b | ...
type Msg = M1 Msg1 | M2 Msg2 | ...

然后,我想分别处理所有这些(我知道该怎么做)。

不过,我的视图功能有问题。我将我的观点定义如下:

view : Model -> Html Msg
view model =
  let v1 = view1 model.model1
      ...
  in ...

view1 : Model1 -> Html Msg1
view1 model = ...

问题是,view1的结果是Html Msg1,而视图函数需要Html Msg

有没有办法将结果从Html Msg1 转换为Html Msg

【问题讨论】:

    标签: elm elm-architecture


    【解决方案1】:

    你正在寻找Html.map:

    view : Model -> Html Msg
    view model =
      let v1 = view1 model.model1 |> Html.map M1
          v2 = view2 model.model2 |> Html.map M2
      in ...
    

    【讨论】:

      猜你喜欢
      • 2017-07-30
      • 2016-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 2017-02-12
      相关资源
      最近更新 更多