Elm - 将 Msg 转换为 Cmd Msg
Elm - Turn Msg into Cmd Msg
我正在尝试从 elm-lang tutorial 修改一个简单的应用程序以首先更新模型,然后触发另一个更新。
update msg model =
case msg of
MorePlease ->
(model, getRandomGif model.topic)
NewGif (Ok newUrl) ->
( { model | gifUrl = newUrl }, Cmd.none)
NewGif (Err _) ->
(model, Cmd.none)
-- my addition
NewTopic newTopic ->
({ model | topic = newTopic}, MorePlease)
这在编译器中失败,因为 NewTopic 分支:
The 3rd branch has this type:
( { gifUrl : String, topic : String }, Cmd Msg )
But the 4th is:
( { gifUrl : String, topic : String }, Msg )
所以我的 Msg 需要输入 Cmd Msg。我怎样才能将我的 Msg 变成 Cmd Msg?
注意:我知道有一种更简单的方法可以进行此更改,但我正试图从根本上理解 Elm
实在没必要把Msg
变成Cmd Msg
。请记住 update
只是一个函数,因此您可以递归调用它。
您的 NewTopic
案例处理程序可以简化为:
NewTopic newTopic ->
update MorePlease { model | topic = newTopic}
如果您真的希望 Elm 架构针对这种情况触发 Cmd,您可以对 Cmd.none
进行简单的 map
到您想要的 Msg
:
NewTopic newTopic ->
({ model | topic = newTopic}, Cmd.map (always MorePlease) Cmd.none)
(实际不推荐)
添加以下函数:
run : msg -> Cmd msg
run m =
Task.perform (always m) (Task.succeed ())
您的代码将变成:
NewTopic newTopic ->
({ model | topic = newTopic}, run MorePlease)
我正在尝试从 elm-lang tutorial 修改一个简单的应用程序以首先更新模型,然后触发另一个更新。
update msg model =
case msg of
MorePlease ->
(model, getRandomGif model.topic)
NewGif (Ok newUrl) ->
( { model | gifUrl = newUrl }, Cmd.none)
NewGif (Err _) ->
(model, Cmd.none)
-- my addition
NewTopic newTopic ->
({ model | topic = newTopic}, MorePlease)
这在编译器中失败,因为 NewTopic 分支:
The 3rd branch has this type:
( { gifUrl : String, topic : String }, Cmd Msg )
But the 4th is:
( { gifUrl : String, topic : String }, Msg )
所以我的 Msg 需要输入 Cmd Msg。我怎样才能将我的 Msg 变成 Cmd Msg?
注意:我知道有一种更简单的方法可以进行此更改,但我正试图从根本上理解 Elm
实在没必要把Msg
变成Cmd Msg
。请记住 update
只是一个函数,因此您可以递归调用它。
您的 NewTopic
案例处理程序可以简化为:
NewTopic newTopic ->
update MorePlease { model | topic = newTopic}
如果您真的希望 Elm 架构针对这种情况触发 Cmd,您可以对 Cmd.none
进行简单的 map
到您想要的 Msg
:
NewTopic newTopic ->
({ model | topic = newTopic}, Cmd.map (always MorePlease) Cmd.none)
(实际不推荐)
添加以下函数:
run : msg -> Cmd msg
run m =
Task.perform (always m) (Task.succeed ())
您的代码将变成:
NewTopic newTopic ->
({ model | topic = newTopic}, run MorePlease)