score:27

Accepted answer

your problem is scoping.

the this that you're trying to access inside the txt() function is pointing to its own this, and not the outer component this.

there are several ways to fix this. here's a few:

use arrow functions

you can transform txt into an arrow function to use the outer this:

render() {
    const txt = (n) => {
        return this.state.bar[this.state.foo][n];
    }
    return (
        <view>
            ...  
        </view>
    );
}

you can bind the function to use the outer this

render() {
    function _txt(n){
        return this.state.bar[this.state.foo][n];
    }


    const txt = _txt.bind(this);

    return (
        <view>
            ...  
        </view>
    );
}

you can create an additional variable that points to the outer this

render() {
    const self = this;
    function txt(n){
        return self.state.bar[self.state.foo][n];
    }
    return (
        <view>
            ...  
        </view>
    );
}

other approaches

  • you can move the txt function to outside of the render function and bind it to the component this.
  • you can use an arrow function inside the component class block, which will seem like you've bound it to the component's this.
  • you can pass the state as a parameter to the function

...and i'm sure that there are several other ways to fix this behaviour. you just need to know when you're using the component's this or some other this.

score:1

a few issues here. first, you need to bind the text function to the class in the constructor. you also need to move the text function out of the render method and add it as a class method (no function in front of function name):

import react,
{ component }
  from 'react';
import {
...
} from 'react-native';

export default class app extends react.component {

  constructor () {
    super();
    this.state = {
      foo: 'abc',
      bar: {
        'abc': [
          '...',
          '...',
          '...'
        ]
      }
    };
    this.text = this.text.bind(this);
  }

  text (n) {
    return this.state.bar[this.state.foo][n];
  }

  render() {
    return (
      <view>
        ...
      </view>
    );
  }
}

Related Query

More Query from same tag