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

這是最近在React Native Android端碰到的一個(gè)比較奇怪的問題,
初看錯(cuò)誤信息與堆棧日志,還是有點(diǎn)懵逼,根據(jù)堆棧信息找到ReactShadowNodeImpl.java這個(gè)類,具體拋錯(cuò)方法:

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

某個(gè)child.mYogaNode == null拋出的,看文檔解釋ReactShadowNodeImpl.java這個(gè)類是模擬React虛擬DOM節(jié)點(diǎn)的基類,暫時(shí)繞開內(nèi)部邏輯,可以確定是View層面上的問題,而且問題拋在渲染某個(gè)固定頁(yè)面上,通過控制變量很快就鎖定在一句引發(fā)問題的代碼上了,邏輯類似如下代碼

render() {
  return(
    this.state.amount &&
       <View>
         <Text>
           hello world
         </Text>
       </View>
  );
}

原來是amount值返回了number類型的0,然后該View的返回值就是number類型,RN處理View的框架代碼估計(jì)只處理了undefined, null, false等錯(cuò)誤類型,未處理返回number類型所導(dǎo)致的錯(cuò)誤,在此也不建議這種寫法的代碼,最好還是老實(shí)使用三目運(yùn)算符,改成如下

render() {
  return(
    this.state.amount ?
       <View>
         <Text>
           hello world
         </Text>
       </View> : null
  );
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容