I am using React Native
for my application, and at one point, I noticed that I have to type this.state.bar[this.state.foo][SOME_NUMBER]
every time, within my components.
This works perfectly fine, but I want to make my code cleaner by calling a function instead. So, I constructed this:
function txt(n){
return this.state.bar[this.state.foo][n];
}
However, when I run this in the Expo
client, I get the following error:
TypeError: undefined is not an object (evaluating 'this.state.bar')
This error is located at:
in App...
....
Here is my entire code.
import React,
{ Component }
from 'react';
import {
...
} from 'react-native';
export default class App extends React.Component {
state = {
foo: 'ABC',
bar: {
'ABC': [
'...',
'...',
'...'
]
}
};
render() {
function txt(n){
return this.state.bar[this.state.foo][n];
}
return (
<View>
...
</View>
);
}
}
I tried placing the text()
function outside the App
class, but got the same error.
When I placed it outside render()
in App
, I got an unexpected token
error.
When I defined this.state
within a constructor(props)
and placed text()
within the constructor
, I got ReferenceError: Can't find variable: text