如果我有一个祖父母、一个子组件和一个孙子组件,那么祖父母可以请求子组件的状态吗?我尝试过像here一样使用"request“,但是当你请求一个也有它自己的子元素的子元素的状态时,类型不匹配。当我请求没有孩子的孩子的状态时,指南中的示例运行良好。
错误是:
Could not match type
Query
with type
Coproduct (Coproduct Query (ChildF AnswerSlot Query)) Query发布于 2016-07-15 18:20:37
是的,当然。您可能只是在对子对象的查询中缺少了一个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 nexthttps://stackoverflow.com/questions/38389322
复制相似问题