我已经成功实现了elm tutorial的删除播放器方法。但是,如果不手动发送ForchFetch
消息(通过单击按钮)再次从服务器获取播放器,我无法更新模型。这是我的代码:
我的删除按钮:
deleteBtn : Player -> Html.Html Msg
deleteBtn player =
let
message =
Msgs.Delete player
in
a
[ class "btn regular", onClick message]
[ i [ class "fa fa-pencil mr1" ] [], text "Delete" ]
我的删除邮件:
type Msg =
| Delete Player
| OnDeletePlayer (Result Http.Error Player)
| ForceFetch
| OnFetchPlayers (WebData (List Player))
我的更新功能:
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
Msgs.ForceFetch ->
(model, fetchPlayers)
Msgs.OnFetchPlayers response ->
( { model | players = response }, Cmd.none )
Msgs.Delete player ->
(model, deletePlayerCmd player)
Msgs.OnDeletePlayer (Ok player) ->
(updateDeletedPlayerList model player, Cmd.none)
Msgs.OnDeletePlayer (Err player) ->
(model, Cmd.none)
updateDeletedPlayerList : Model -> Player -> Model
updateDeletedPlayerList model deletedPlayer =
let
updatedPlayers = RemoteData.map (List.filter (\p -> deletedPlayer /= p)) model.players
in
{ model | players = updatedPlayers}
deletePlayerCmd : Player -> Cmd Msg
deletePlayerCmd player =
Http.send Msgs.OnDeletePlayer (deletePlayerRequest player)
deletePlayerRequest : Player -> Http.Request Player
deletePlayerRequest player =
Http.request
{ body = Http.emptyBody
, expect = Http.expectJson playerDecoder
, headers = []
, method = "DELETE"
, timeout = Nothing
, url = savePlayerUrl player.id
, withCredentials = False
}
fetchPlayers : Cmd Msg
fetchPlayers =
Http.get fetchPlayersUrl playersDecoder
|> RemoteData.sendRequest
|> Cmd.map Msgs.OnFetchPlayers
为了衡量我的模型:
type alias Model =
{ players : WebData (List Player)
, route : Route
, newPlayerName : String
, newPlayerId : String
, newPlayerLevel : Int
}
编辑:
我尝试以下列方式合并fetchPlayers
但没有成功:
Msgs.OnDeletePlayer (Ok player) ->
(updateDeletedPlayerList model player, fetchPlayers)
如果您不希望在删除后获取模型,则需要在代码中更新模型,因此您需要:
Msgs.Delete player ->
(model, deletePlayerCmd player)
你需要将'model'更改为一个将从中移除玩家的函数:
Msgs.Delete player ->
(removePlayer player model, deletePlayerCmd player)
...
removePlayer : Player -> Model -> Model
...