Friday 18 January 2019

javascript - Variable undefined when used outside of component constructor



I'm working on a project with React and Electron and have an error. I have a component with a constructor that takes in props (which come in the form of two variables.) The constructor is instantiated in a separate file. The issue is that the variable works fine (for instance if do console.log to output it) in the constructor, but outside of it, the variables comes back undefined.



I've already tried using .bind to bind it, but that didn't help and it still turned up as undefined.




This is where the constructor is called:



const dropDown = new Dropdown({
editor,
monaco
});


Here is the constructor and an example of where I am trying to use the variables:




constructor(props) {
super(props);

// Define variables
this.editor = props.editor;
this.monaco = props.monaco;
// Returns correct object
console.log(this.monaco);


// Bind functions
this.changeLanguage = this.changeLanguage.bind(this);
this.filterFunction = this.filterFunction.bind(this);
this.dropDown = this.dropDown.bind(this);
}

changeLanguage(language) {
// Returns undefined all the time
console.log(this.monaco);
this.monaco.editor.setModelLanguage(this.editor, language);

}


I expect the variable to be the same in both the constructor and the functions elsewhere in the file, yet for some reason, it's only defined in the constructor.


Answer



You can use this.props.monaco. Or you can pass the props to the changeLanguage function if you rewrite it



changeLanguage(language, props) {
// Returns undefined all the time
console.log(props.monaco);

props.monaco.editor.setModelLanguage(this.editor, language);
}


and call it: this.changeLanguage('English', this.props)


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...