React Native中在mapObject回调返回值内调用test函数报错的解决方法
解决React Native中map回调里调用组件方法报错的问题
首先,你遇到的"teste() is not a function"(应该是test()的笔误吧?)错误核心原因是回调函数里的this指向不对——你在mapObject的回调里用了普通function,它会创建自己的上下文,导致this不再指向你的React组件实例,自然找不到test方法。另外你的mapObject函数也有小问题,我一起帮你修正。
一、修正this指向的几种方案
方案1:使用箭头函数作为回调(最推荐)
箭头函数不会绑定自己的this,会继承外层作用域的this(也就是你的组件实例),这样就能直接调用this.test了:
render() { return ( <View> {this.mapObject(this.state.JSONreturn, (key) => { // 这里改成箭头函数 return ( <Text>{key.number1} / {this.test(key.number1, key.number2)}</Text> ) })} </View> ) }
方案2:给回调函数绑定this
如果坚持用普通function,可以通过bind(this)把组件的this绑定到回调里:
render() { return ( <View> {this.mapObject(this.state.JSONreturn, function (key) { return ( <Text>{key.number1} / {this.test(key.number1, key.number2)}</Text> ) }.bind(this))} {/* 这里绑定this */} </View> ) }
方案3:提前保存this到变量
在render里先把组件的this存到一个变量(比如that),然后在回调里用这个变量调用方法:
render() { const that = this; // 保存组件的this return ( <View> {this.mapObject(this.state.JSONreturn, function (key) { return ( <Text>{key.number1} / {that.test(key.number1, key.number2)}</Text> {/* 用that代替this */} ) })} </View> ) }
二、修正你的mapObject函数
另外注意:如果this.state.JSONreturn是数组,其实你可以直接用数组原生的map方法,不用自己封装;如果它是对象,那你当前的mapObject函数有问题——因为对象没有map方法,需要遍历对象的键:
// 如果处理的是对象,修正后的mapObject mapObject(object_, callback) { if (!object_) return []; // 遍历对象的键,拿到每个键对应的值 return Object.keys(object_).map(key => { return callback(object_[key], key); // 把值和键传给回调 }); }
如果是数组的话,其实完全可以去掉mapObject,直接写:
{this.state.JSONreturn.map((item) => ( <Text key={item.id}>{item.number1} / {this.test(item.number1, item.number2)}</Text> ))}
三、额外建议
- 组件里的方法可以用箭头函数定义,避免后续绑定
this的问题:
test = (v1, v2) => { return v1 - v2; }
- 记得给列表项加
key属性,这是React的要求,避免警告:
<Text key={key.id}>{key.number1} / {this.test(key.number1, key.number2)}</Text>
内容的提问来源于stack exchange,提问作者Pedro Marques
相关产品推荐
相关产品推荐

