這是最近在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
);
}