问题描述
在榆树中,我有一个包含 currentDate
的模型,它是一个表示日期的字符串。我用一个信号更新:
In elm I have a model that includes a currentDate
, it's a string representing the date. I update it with a signal:
Signal.map (SetCurrentDate << timeToDateString) (Time.every Time.second)
SetCurrentDate
是更新模型的动作( SetCurrentDate date - > {model | currentDate< - date}
)和 timeToDateString
将时间转换为字符串如yyyy-mm-dd。
SetCurrentDate
is an action that updates the model (SetCurrentDate date -> { model | currentDate <- date}
), and timeToDateString
converts from time to a string like "yyyy-mm-dd".
但是,有两个问题:
-
model.currentDate
只能在一秒后正确设置。所以在应用程序的开始有一秒钟,当前的日期没有正确设置。 -
model.currentDate
每秒设置一次,即使它每天都在变化。
model.currentDate
is only correctly set after one second. So there's a second at the start of the app where the currentDate is not properly set.model.currentDate
is set every second, even though it only changes every day.
有没有办法解决这个问题?所以currentDate是设置在应用程序的开始(没有一秒的延迟),而且它每天只更新一次?
Is there a way to fix this? So the currentDate is set at the start of the app (without the one second delay), and that it's only updated one a day?
额外的发现:
如果我将信号更改为 Signal.dropRepeats< | Signal.map(SetCurrentDate<< timeToDateString)(Time.every Time.second)
(所以我放弃重复),信号只在当天发生变化时被触发,也不会在开始应用程序。
If I change the signal to Signal.dropRepeats <| Signal.map (SetCurrentDate << timeToDateString) (Time.every Time.second)
(so I drop the repeats), the signal is only fired when the day changes, and not also once on the start of the app.
编辑:如果在Elm应用程序中有更好的方式了解currentDate,我很乐意听到。我的谷歌没有任何东西。
If there is a better way of knowing the currentDate in an Elm application, I would love to hear it. My Googling gave nothing.
谢谢!
推荐答案
/ h1>
您是否使用 StartApp
或者您有自己的 foldp
?如果您正在使用 StartApp
,最好查找开始
函数的代码,并内联它,以便您可以访问 foldp
。
Using Signals
Are you using StartApp
or do you have your own foldp
? If you are using StartApp
it's best to look up the code for the start
function and inline it so you have access to the foldp
.
Signal.foldp
对信号的初始值不做任何事情。因此,如果您使用 Time.every Second
信号,则只能在一秒钟后获取更新,只有在使用日期转换后的一天内才能获得 Signal.dropRepeats
。您可以使用从第三方 library *来修复。它需要一个功能来从输入的初始值创建 foldp
的初始状态。
Signal.foldp
doesn't do anything with the initial value of a signal. So if you use the Time.every second
signal, you only get your update after a second, and only after a day if you use the date conversion and Signal.dropRepeats
. You can use Signal.Extra.foldp'
from the 3rd party signal-extra library* to fix that. It takes a function to create the initial state of the foldp
from the initial value of the input.
*全面披露:我是图书馆的作者
*Full disclosure: I'm the author of the library
在库调用。我认为这可以满足您的需求,而不需要每秒更新一次的信号。除了,你可能会得到一些只能每天检查一次或两次的东西。
There is a very useful task in the task-tutorial library called getCurrentTime
. I think that can serve your needs without needing a signal that updates every second. Along with Task.sleep
, you can probably get something that only checks the time once or twice a day.
这篇关于榆树当前日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!