SectionList与mobx不兼容的解决方案:Attempt to read an array index (4) that is out of bounds (4).

前几天在使用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)."的解决方案,希望对你有所帮助。如有帮助,记得点赞哦~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值