将标志转换为模型的Elm方法
我的应用程序中有以下类型:将标志转换为模型的Elm方法,elm,Elm,我的应用程序中有以下类型: type Page = Welcome | Cards type alias Flags = { recipientName : String , products : List Product } type alias Product = { id : Int , name : String , price : Float , liked : Maybe Bool } typ
type Page
= Welcome
| Cards
type alias Flags =
{ recipientName : String
, products : List Product
}
type alias Product =
{ id : Int
, name : String
, price : Float
, liked : Maybe Bool
}
type alias Model =
{ recipientName : String
, currentPage : Page
, products : List Product
}
我将传递一系列产品作为标志。下面是我的init
的样子:
init : Flags -> ( Model, Cmd Msg )
init flags =
let
{ recipientName, products } =
flags
in
Model recipientName Welcome products
|> withNoCmd
我面临的挑战是,此阵列中的产品只有
id
、name
和price
属性。因此,给定标志
定义,每次我使用新属性(例如like
)扩展产品
,作为标志传递的产品数组也需要具有该属性。现在,我只是将它们渲染为空,但这感觉不太对,所以我想知道Elm的方式是什么™ 接收标志并将其转换为模型?谢谢大家! 听起来您的产品
已经被定义为应用程序的输入(或环境):
type alias Product =
{ id : Int
, name : String
, price : Float
}
您正在使用与收件人和产品相关的信息来增强此功能。我建议将其拆分为自己的类型,并随着应用程序的增长而增长,例如:
type alias Opinion =
{ liked : Maybe Bool
, review : String
, preferredColor : Color
}
然后,您可以在您的模型中将这些连接在一起:
type alias Model =
{ recipientName : String
, currentPage : Page
, products : List (Product, Opinion)
}
或者,根据应用程序的工作方式,您可能最终希望通过product.id
:
...
, products : List Product
, opinions : Dict Int Opinion
关键是,如果您保持原始产品
不变,您可以为库存(不涉及收件人)和客户构建一个小型函数库,用于产品
。也许您可以对客户指标重复使用意见
类型
如果这两种类型可能会演变,将它们分开有助于确保最终不会出现混乱和吸引bug的相互依赖关系