在PureScript Halogen项目中,我想将状态设置为随机数,但如何提取值?正常
r <- randomInt 1 10
在eval函数内部时不编译。
module Main where
import Prelude
import Control.Monad.Eff (Eff)
import Control.Monad.Eff.Random (randomInt, RANDOM)
import Halogen as H
import Halogen.HTML.Events.Indexed as HE
import Halogen.HTML.Indexed as HH
import Halogen.Util (runHalogenAff, awaitBody)
type State = { n::Int }
initialState :: State
initialState = { n: 3}
data Query a = NewRandom a
ui :: forall e. H.Component { n :: Int } Query e
ui =
H.component { render, eval }
where
render :: State -> H.ComponentHTML Query
render state =
HH.button
[ HE.onClick $ HE.input_ NewRandom ]
[ HH.text $ show state.n ]
eval :: Query ~> H.ComponentDSL State Query e
eval (NewRandom next) = do
H.modify (\state -> state { n=12 } )
--I'd like to set n to a random number
--but I don't know how.
--let r = randomInt 1 10
--H.modify (\state -> state { n=r } )
pure next
main :: Eff (H.HalogenEffects ()) Unit
main =
runHalogenAff do
body <- awaitBody
H.runUI ui initialState body
答案 0 :(得分:3)
您需要在ComponentDSL
(当前有e
类型var)的地方使用适当的monad才能实现,然后您可以使用H.fromEff
解除{ {1}}:
randomInt
(旁白:如果您正在做有效的事情,即使您只需要module Main where
import Prelude
import Control.Monad.Aff (Aff)
import Control.Monad.Eff (Eff)
import Control.Monad.Eff.Random (randomInt, RANDOM)
import Halogen as H
import Halogen.HTML.Events.Indexed as HE
import Halogen.HTML.Indexed as HH
import Halogen.Util (runHalogenAff, awaitBody)
type State = { n::Int }
initialState :: State
initialState = { n: 3}
data Query a = NewRandom a
ui :: forall eff. H.Component { n :: Int } Query (Aff (random :: RANDOM | eff))
ui =
H.component { render, eval }
where
render :: State -> H.ComponentHTML Query
render state =
HH.button
[ HE.onClick $ HE.input_ NewRandom ]
[ HH.text $ show state.n ]
eval :: Query ~> H.ComponentDSL State Query (Aff (random :: RANDOM | eff))
eval (NewRandom next) = do
r <- H.fromEff $ randomInt 1 10
H.modify (\state -> state { n=r } )
pure next
main :: forall eff. Eff (H.HalogenEffects (random :: RANDOM | eff)) Unit
main =
runHalogenAff do
body <- awaitBody
H.runUI ui initialState body
,最简单的方法是使用Eff
作为Aff
monad,就像使用{{1}时一样它期望它是ComponentDSL
- 可以使用runUI
模块中的Aff
来更改monad,但是因为你只是在那里使用interpret
无论如何,你也可以直接去Halogen.Component
。)
请查看"Non-state effects" section of the guide或AJAX example,了解有关interpret liftAff
中运行效果的更多详情。