score:2

Accepted answer

you need to bind showstatus in your constructor. the component lifecycle methods are so bound by default.

you need to add a constructor like so:

constructor(props) {
   super(props)
   this.showstatus = this.showstatus.bind(this);
}

without doing so 'this' will be null in that method.

score:-1

in react you return entire component tree you want to render in the render method. in your case you return react nodes in the asynchronous callback of click handler. basically they are ignored. to fix this you need to save network call result like this: this.setstate({myarray: myarray}) and then in render method you would check if myarray is present in the state and if present render it.

score:0

i will explain how this work with react, first let's take this example:

import react from "react";
import "./styles.css";

class app extends react.component {
 hi(){
 console.log("hi")
  }
  click() {
    console.log(this);
    this.hi();
  }
  render() {
    return (
      <div classname="app">
        <h1>hello codesandbox</h1>
        <h2>start editing to see some magic happen!</h2>
        <button onclick={this.click}>click</button>
      </div>
    );
  }
}

export default app;

here this example will give an error because the click function got different scope then the hi() function if you try to see console.log(this) this will return the show global window object so if we do this :

import react from "react";
import "./styles.css";

window.hi = () => {
  console.log("hi");
};

class app extends react.component {
  click() {
    console.log(this);
    this.hi();
  }
  render() {
    return (
      <div classname="app">
        <h1>hello codesandbox</h1>
        <h2>start editing to see some magic happen!</h2>
        <button onclick={this.click}>click</button>
      </div>
    );
  }
}

export default app;

now it will work because the function click environment is the global window. in this case this work ok but what if you got to manage component state in your click function here where this will not work because state is only for react.component and that why you need to bind the click to the component scope so that it will be able to access react.component methods and you can do this with several ways but i prefer arrow function auto binding like this :

 click =()=> {
    console.log(this);
    this.hi();
  } 

Related Query

More Query from same tag