om组件应该返回什么以不呈现任何内容? [英] What should an om component return to render nothing?

查看:55
本文介绍了om组件应该返回什么以不呈现任何内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以编写一个不呈现任何内容的组件,例如,如果其光标数据为空?

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

我做不到

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

if子句返回nil,会导致错误消息

The if clause returns nil, which causes an error message


未捕获的错误:始终违反:ReactCompositeComponent.render():
必须返回有效的ReactComponent。您可能返回了null,
未定义,数组或其他无效对象。

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 ?

推荐答案

我的理解之所以不能这样做,是因为React需要跟踪DOM中的组件,并通过向节点添加react-id属性来做到这一点。
如果您呈现 nothing,则React不知道如何将其安装到DOM(实际上已卸载)。由于您无法安装已卸载的组件,因此不允许这样做。

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.

解决方案将具有非空组件状态是其自己的组件,然后让PARENT有条件地构建该组件。这样,如果您不希望渲染任何内容,则它将卸载该组件,并且..则不渲染任何内容。

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))))))

这篇关于om组件应该返回什么以不呈现任何内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆