1

I have a code like this:

//my_file.js

var React = require('react');
var ReactDom = require('react-dom');
var App = React.createClass({
    getInitialState:function(){
        return {//something};
    },
    myFunction:function(html){
        //some code
    },
    render:function(){
        //some code
        var someVar1, someVar2, someVar3;
        someVar1.map( function(i, j){
            someVar2.campos.map( function(k, j){
                someVar3.campos.map( function(z, k){
                    this.myFunction(something);
                }
            }
        }
        return (
            <div>
                { //something }
            </div>
        );
    }
});
module.exports=App;

my_file.js:16 Uncaught TypeError: this.myFunction is not a function. What I'm doign wrong? How I use that function inside the render?

1
  • this inside a function is probably points to window object not your component object. Commented Oct 27, 2016 at 15:37

1 Answer 1

3

Problem is that in .map this refers to global scope not to your component. There are several ways how you can solve this problem

  1. set this for each .map

    someVar1.map( function(i, j){
      someVar2.campos.map( function(k, j){
        someVar3.campos.map( function(z, k){
          this.myFunction(something);
        }, this);
      }, this)
    }, this)
    
  2. store this in variable

    var self = this;
    someVar1.map( function(i, j){
      someVar2.campos.map( function(k, j){
        someVar3.campos.map( function(z, k){
          self.myFunction(something);
        });
      })
    })
    
  3. use arrow functions

    someVar1.map( (i, j) => {
      someVar2.campos.map( (k, j) => {
        someVar3.campos.map( (z, k) => {
          this.myFunction(something);
        });
      })
    })
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.