React Native中,this.'function'不是一个函数。

15

我正在学习React Native和Redux,这里有许多与我的问题类似的问题,但我很难将它们与我的问题联系起来。

当我在另一个方法中调用一个方法时,它一直返回给我“'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方法中调用的函数引起了错误。

我感激任何解决这个问题的建议。


props 是从哪里来的?你能添加整个代码吗? - Sebastián Palma
1个回答

24

这是一个绑定问题。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并不指向你的类,而是指向该函数本身。只需要执行以下操作:

this并非指向您的类,而是指向函数本身。只需执行以下操作:

return this.props.orders.map((order) => {  
  return (
    <Panel title={order.id} key={order.id}>
      <Text>Item: {this.displayItems(order)}{'\n'}</Text>
    </Panel>);
});

箭头函数没有自己的上下文,所以这应该适用于您。您也可以调用bind,但我认为箭头函数的解决方案更简单。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接