我正在学习 React Native 和 Redux,这里有很多类似的问题,但我很难与我的问题联系起来。
当我在另一个方法中调用一个方法时,它一直返回给我 this.'some function' 不是一个函数,我真的不知道该怎么做。
这是我的一些代码..
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 方法中的函数调用会导致错误。
我感谢任何解决此问题的建议。
最佳答案
这是一个有约束力的问题。 JavaScript 中的函数有自己的 this
除非另有明确说明,否则上下文,所以当你这样做时
return this.props.orders.map(function(order) {
return (
<Panel title={order.id} key={order.id}>
<Text>Item: {this.displayItems(order)}{'\n'}</Text>
</Panel>);
});
this
不是指向您的类,而是指向函数本身。只需执行以下操作return this.props.orders.map((order) => {
return (
<Panel title={order.id} key={order.id}>
<Text>Item: {this.displayItems(order)}{'\n'}</Text>
</Panel>);
});
箭头函数没有自己的上下文,所以这应该适合你。您也可以调用
bind
,但我认为箭头函数解决方案更简单。
关于react-native - React Native this .'function' is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43218451/