React Native this.'function' 不是函数 [英] React Native this.'function' is not a function
问题描述
我正在学习 React Native 和 Redux,这里有许多类似的问题,但我很难解决我的问题.
I'm in the middle of learning React Native and Redux and there are many similar problems to mine in here but I'm having a hard time to relate with my problem.
当我在另一个方法中调用一个方法时,它一直向我返回 this.'some function' 不是一个函数,我真的不知道该怎么做.
When I invoke a method in another method, it keeps returning me this.'some function' is not a function and I really have no idea what to do.
这是我的一些代码..
import React, { Component } from 'react';
import { Text, StyleSheet, ScrollView } from 'react-native';
import { connect } from 'react-redux';
import Panel from '../components/panel';
class Orders extends Component {
displayItems(obj) {
console.log('itemArr', obj);
return obj.items.map(function(item){
return (<Text>{item.quantity + ' ' + item.name}</Text>)
});
}
renderContents() {
console.log('orders', this.props.orders);
if (!this.props.orders) {
return <Text>Loading...</Text>;
}
return this.props.orders.map(function(order) {
return (
<Panel title={order.id} key={order.id}>
<Text>
Item: {this.displayItems(order)}{'\n'}
</Text>
</Panel>
);
});
}
render() {
return(
<ScrollView style={styles.container}>
{this.renderContents()}
</ScrollView>
);
}
}
我不知道为什么 render 方法中的函数不会导致任何错误,但我的 renderContents 方法中的函数会导致任何错误.
I'm not sure why the function inside of render method does not cause any error but the function invoke in my renderContents method does.
我感谢任何解决此问题的建议.
I appreciate any advice to get around this problem.
推荐答案
这是一个绑定问题.JavaScript 中的函数有自己的 this
上下文,除非另有明确说明,所以当你这样做时
This is a binding issue. Functions in JavaScript have their own this
context unless explicitly told otherwise, so when you do
return this.props.orders.map(function(order) {
return (
<Panel title={order.id} key={order.id}>
<Text>Item: {this.displayItems(order)}{'\n'}</Text>
</Panel>);
});
this
不是指向你的类,而是指向函数本身.只需执行以下操作
this
is not pointing to your class, but to the function itself. Just do the following
return this.props.orders.map((order) => {
return (
<Panel title={order.id} key={order.id}>
<Text>Item: {this.displayItems(order)}{'\n'}</Text>
</Panel>);
});
箭头函数没有自己的上下文,所以这应该适合你.你也可以调用 bind
,但我认为箭头函数的解决方案更简单.
Arrow functions do not have their own context, so this should work for you. You could also call bind
, but I think the arrow function solution is simpler.
这篇关于React Native this.'function' 不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!