榆木-将Msg转换为Cmd Msg [英] Elm - Turn Msg into Cmd Msg
问题描述
我正在尝试从 elm-lang教程修改一个简单的应用程序首先更新模型,然后触发另一个更新.
I'm trying to modify a simple app from the elm-lang tutorial to first update the model, then trigger another update.
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分支:
This fails in the compiler because the NewTopic branch:
The 3rd branch has this type:
( { gifUrl : String, topic : String }, Cmd Msg )
But the 4th is:
( { gifUrl : String, topic : String }, Msg )
因此,我的消息需要输入Cmd Msg.如何将我的消息"转换为Cmd消息?
So my Msg needs to be type Cmd Msg. How can I turn" my Msg into a Cmd Msg?
注意:我认识到有一种更简单的方法来进行此更改,但我想从根本上理解Elm
推荐答案
实际上没有必要将 Msg
转换为 Cmd Msg
.请记住, update
只是一个函数,因此您可以递归调用它.
There is really no need to turn Msg
into a Cmd Msg
. Remember that update
is just a function, so you can call it recursively.
您的 NewTopic
案例处理程序可以简化为:
Your NewTopic
case handler can be simplified to this:
NewTopic newTopic ->
update MorePlease { model | topic = newTopic}
如果您确实希望Elm Architecture在这种情况下触发Cmd,则可以将 Cmd.none
的简单 map
映射到所需的消息
:
If you really truly wanted the Elm Architecture to fire off a Cmd for this scenario, you could do a simple map
of Cmd.none
to your desired Msg
:
NewTopic newTopic ->
({ model | topic = newTopic}, Cmd.map (always MorePlease) Cmd.none)
(实际上不推荐)
这篇关于榆木-将Msg转换为Cmd Msg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!