ckim16
ckim16

Reputation: 1749

React Native this.'function' is not a function

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.

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.

Here are some of my code..

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>
        );
    }
}

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.

Upvotes: 15

Views: 30105

Answers (1)

martinarroyo
martinarroyo

Reputation: 9701

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 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>);
});

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.

Upvotes: 24

Related Questions