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.
The React. js "Uncaught TypeError: X is not a function" occurs when we try to call a value that is not a function as a function, e.g. calling the props object instead of a function. To solve the error, console. log the value you are calling and make sure it is a function.
First, create a React project by typing inside the terminal. To execute a external JavaScript function, we need to put the name of the function “alertHello” inside the square bracket. If you click on the alert button, it should popup the alert “Hello”. This imply we can call the external JavaScript function from React.
First declare the state at: {name, setName} = useState(''); This allows us to get name and call setName , and gives it an initial value of '' . This causes your component to rerender itself, and then you can use the name property in your render method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With