我正在尝试一个简单的Elm CRUD示例,但是当我将新项目添加到模型中的项目列表时,DOM不会重新渲染。
现在,我只是添加一个静态记录,我可以通过elm-reactor调试器确认模型正在更改,但映射的itemView项目没有使用新的div元素进行更新。
我觉得我可能会错过Elm架构/虚拟dom的一个非常重要的部分。任何人都可以指出我正确的方向吗?
import Html exposing (Html, text, beginnerProgram, div, input, button)
import Html.Events exposing (onInput, onClick)
import List exposing (map, repeat, append)
main =
Html.beginnerProgram
{ model = model
, view = view
, update = update }
type alias Model =
{ items : List Item
, inputTxt : String }
model : Model
model =
{ items = items
, inputTxt = inputTxt }
type alias Item =
{ id : Int
, txt : String }
item : Item
item =
{ id = 0
, txt = "some text" }
items : List Item
items =
repeat 2 item
inputTxt : String
inputTxt =
""
type Msg
= NoOp
| ChangeTxt String
| AddItem
update : Msg -> Model -> Model
update msg model =
case msg of
NoOp ->
model
ChangeTxt newTxt ->
{ model | inputTxt = newTxt }
AddItem ->
{ model | items = model.items ++ [{ id = 0, txt = "some text" }] }
view : Model -> Html Msg
view model =
div [] [
div [] [ itemsView items ]
, div [] [
input [ onInput ChangeTxt ] []
]
, div [] [
text model.inputTxt
]
, div [] [
button [ onClick AddItem ] [ text "click me!" ]
]
]
itemView : Item -> Html Msg
itemView item =
div [] [
div [] [ text ( toString item.id ) ]
, div [] [ text item.txt ]
]
itemsView : List Item -> Html Msg
itemsView items =
div [] [
div [] (List.map itemView items)
]
答案 0 :(得分:8)
view
函数的第二行应为
div [] [ itemsView model.items ]
现在它始终呈现上面定义的items
,而不是模型中的项目。