前几天在使用SectionList与mobx合用的时候,遇到了这个warning警告:"Attempt to read an array index (4) that is out of bounds (4). Please check length first. Out of bound indices will not be tracked by MobX"
项目使用的版本号如下:
"mobx": "^4.3.1",
"mobx-react": "^5.1.0",
"react": "16.9.0",
"react-native": "0.61.5
出现了这个黄色警告,其实还是因为React与mobx的兼容性问题。这个错误提示是数组越界,其实还是切片slice的问题,先看下我出现问题的写法:
<SectionList
style={styles.flatListStyle}
renderSectionHeader={this._sectionHeader}
renderItem={this._listItemView}
sections={unGroupStore.listData} //这里是个section格式的数组,直接引用就会报以上的黄色警告
keyExtractor={this._extraUniqueKey}
showsVerticalScrollIndicator={false}
refreshing={false}
bounces={true}/>
再看下在store中是如何赋值的:
import {observable, action} from 'mobx';
...
let arr = [];
arr.push({
key:"1",
data:this.finger.slice() // 仍然会报警告
});
arr.push({
key:"2",
data:this.cipher.slice()
});
arr.push({
key:"3",
data:this.cards.slice()
});
this.listData = [...arr];
修改之后:
import {observable, action,computed} from 'mobx';
//只需要多加这个方法:
@computed
get formattedList(){
return this.listData.map((v)=>{
return {
key: v.key,
data: v.data.slice(),
}
}).slice();
}
同时在render中修改成调用formattedList方法:
<SectionList
style={styles.flatListStyle}
renderSectionHeader={this._sectionHeader}
renderItem={this._listItemView}
sections={unGroupStore.formattedList} //这里调用formattedList方法,就不会有警告了
keyExtractor={this._extraUniqueKey}
showsVerticalScrollIndicator={false}
refreshing={false}
bounces={true}/>
以上即是本人遇到"Attempt to read an array index (4) that is out of bounds (4)."的解决方案,希望对你有所帮助。如有帮助,记得点赞哦~