如果我有祖父母,子组件和孙子组件,祖父母是否可以请求孩子的状态?我尝试过使用"请求"比如here,但当您要求同时拥有自己孩子的孩子的状态时,这些类型不会匹配。当我要求没有孩子的孩子的状态时,指南中的例子工作正常。
错误是:
Could not match type
Query
with type
Coproduct (Coproduct Query (ChildF AnswerSlot Query)) Query
答案 0 :(得分:1)
是的,当然。您可能只是错过了对孩子的查询中的left
- 这是必需的,因为孩子的查询代数将采用Coproduct f (ChildF p f')
形式,因为它具有自己的孩子。
相应地,您也可以通过使用right
并使用适当的孙子值构建ChildF
来查询祖父母的孙子。
我已经汇集了一个人工和孙子问题的人为例子,希望能让事情变得更加清晰:
module Main where
import Prelude
import Data.Functor.Coproduct (Coproduct, left, right)
import Data.Maybe (Maybe(..), fromMaybe)
import Debug.Trace (traceA) -- from purescript-debug
import Halogen as H
import Halogen.HTML as HH
--------------------------------------------------------------------------------
type GrandState = Unit
data GrandQuery a = AskGrandChild (String -> a)
grandchild :: forall g. H.Component GrandState GrandQuery g
grandchild = H.component { render, eval }
where
render :: GrandState -> H.ComponentHTML GrandQuery
render _ = HH.div_ []
eval :: GrandQuery ~> H.ComponentDSL GrandState GrandQuery g
eval (AskGrandChild k) = pure $ k "Hello from grandchild"
--------------------------------------------------------------------------------
type ChildState = Unit
data ChildQuery a = AskChild (String -> a)
type GrandSlot = Unit
type ChildState' g = H.ParentState ChildState GrandState ChildQuery GrandQuery g GrandSlot
type ChildQuery' = Coproduct ChildQuery (H.ChildF GrandSlot GrandQuery)
child :: forall g. Functor g => H.Component (ChildState' g) ChildQuery' g
child = H.parentComponent { render, eval, peek: Nothing }
where
render :: ChildState -> H.ParentHTML GrandState ChildQuery GrandQuery g GrandSlot
render _ = HH.slot unit \_ -> { component: grandchild, initialState: unit }
eval :: ChildQuery ~> H.ParentDSL ChildState GrandState ChildQuery GrandQuery g GrandSlot
eval (AskChild k) = pure $ k "Hello from child"
--------------------------------------------------------------------------------
type ParentState = Unit
data ParentQuery a = Something a
type ChildSlot = Unit
type ParentState' g = H.ParentState ParentState (ChildState' g) ParentQuery ChildQuery' g ChildSlot
type ParentQuery' = Coproduct ParentQuery (H.ChildF ChildSlot ChildQuery')
parent :: forall g. Functor g => H.Component (ParentState' g) ParentQuery' g
parent = H.parentComponent { render, eval, peek: Nothing }
where
render :: ParentState -> H.ParentHTML (ChildState' g) ParentQuery ChildQuery' g ChildSlot
render _ = HH.slot unit \_ -> { component: child, initialState: H.parentState unit }
eval :: ParentQuery ~> H.ParentDSL ParentState (ChildState' g) ParentQuery ChildQuery' g ChildSlot
eval (Something next) = do
-- note the `left` here
childAnswer <- H.query unit $ left $ H.request AskChild
traceA $ fromMaybe "child not found" $ childAnswer
grandAnswer <- H.query unit $ right $ H.ChildF unit $ H.request AskGrandChild
traceA $ fromMaybe "grandchild not found" $ grandAnswer
pure next