What should an om component return to render nothing?

我怕爱的太早我们不能终老 提交于 2019-12-22 07:50:11

问题


Is it possible to write a component that renders nothing, for example, if its cursor data is empty ?

I can not do

(defn count-or-nothing [list-cursor owner]
  (reify
    om/IRender
    (render [_]
       (if (not (empty? list-cursor))
         (dom/div nil "You have some elements !")))))

The if clause returns nil, which causes an error message

Uncaught Error: Invariant Violation: ReactCompositeComponent.render(): A valid ReactComponent must be returned. You may have returned null, undefined, an array, or some other invalid object.

I got by, by rendering an empty span, but that sounds clumsy. Do I necessarily have to refactor my code and get the test "out" of this component ?


回答1:


My understanding of why you cannot do this is because React needs to keep track of the component in the DOM and does this by adding a react-id attribute to the nodes. If you render "nothing", then React doesn't know how to mount it into the DOM (its effectively unmounted). Since you can't have a mounted unmounted component, it doesn't allow this.

The solution would be to have the non-empty state be its own component and then have the PARENT conditionally build that component. That way, if you want to render nothing, it unmounts the component and.. renders nothing.

(defn something-interesting [list-cursor owner]
  (reify
    om/IRender
    (render [_]
      (dom/div nil "You have some elements !"))))

(defn count-or-nothing [list-cursor owner]
  (reify
    om/IRender
    (render [_]
      (dom/div nil
        ; Other UI stuff here maybe...
        (when-not (empty? list-cursor)
          (om/build something-interesting list-cursor))))))



回答2:


So the answer is : you can't do it.

I would mark this as a duplicate of Unable to display two components in OM , but there is no answer on this question...

[EDIT] Fixed the question link



来源:https://stackoverflow.com/questions/24555749/what-should-an-om-component-return-to-render-nothing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!