Error: Cannot add a child that doesn't have a YogaNode to a parent without a measure function!

这是最近在React Native Android端碰到的一个比较奇怪的问题,
初看错误信息与堆栈日志,还是有点懵逼,根据堆栈信息找到ReactShadowNodeImpl.java这个类,具体抛错方法:

public void addChildAt(ReactShadowNodeImpl child, int i) {
    if (child.getParent() != null) {
      throw new IllegalViewOperationException(
        "Tried to add child that already has a parent! Remove it from its parent first.");
    }
    if (mChildren == null) {
      mChildren = new ArrayList<>(4);
    }
    mChildren.add(i, child);
    child.mParent = this;

    // If a CSS node has measure defined, the layout algorithm will not visit its children. Even
    // more, it asserts that you don't add children to nodes with measure functions.
    if (mYogaNode != null && !isYogaLeafNode()) {
      YogaNode childYogaNode = child.mYogaNode;
      if (childYogaNode == null) {
        throw new RuntimeException(
            "Cannot add a child that doesn't have a YogaNode to a parent without a measure "
                + "function! (Trying to add a '"
                + child.toString()
                + "' to a '"
                + toString()
                + "')");
      }
      mYogaNode.addChildAt(childYogaNode, i);
    }
    markUpdated();

    int increase = child.isLayoutOnly() ? child.getTotalNativeChildren() : 1;
    mTotalNativeChildren += increase;

    updateNativeChildrenCountInParent(increase);
  }

某个child.mYogaNode == null抛出的,看文档解释ReactShadowNodeImpl.java这个类是模拟React虚拟DOM节点的基类,暂时绕开内部逻辑,可以确定是View层面上的问题,而且问题抛在渲染某个固定页面上,通过控制变量很快就锁定在一句引发问题的代码上了,逻辑类似如下代码

render() {
  return(
    this.state.amount &&
       
         
           hello world
         
       
  );
}

原来是amount值返回了number类型的0,然后该View的返回值就是number类型,RN处理View的框架代码估计只处理了undefined, null, false等错误类型,未处理返回number类型所导致的错误,在此也不建议这种写法的代码,最好还是老实使用三目运算符,改成如下

render() {
  return(
    this.state.amount ?
       
         
           hello world
         
        : null
  );
}

你可能感兴趣的:(Error: Cannot add a child that doesn't have a YogaNode to a parent without a measure function!)