0

I have a problem with this code. when compiling it shows me twice the message in the console ... it happens with any code that I put, also when I call a method. it is as if the component was run twice when it is class. when it is a function it does not happen, depending on if it is executed only once ... It is not that the message of "Hello world" appears twice, only one appears. but it is as if the component is updated or reloaded when it is class and I get the message in console twice. I am new to react and I would like you to help me with this question please.

import React, { Component } from 'react'

 class Page extends Component {
    getMessage(){
        console.log("hello1")
    }
    render(){console.log("hello2")
        return (
            <div>
                <h2>Hello world</h2>
                {this.getMessage()}
                
            </div>
        )
    }
}
export default Page;
  • Does this answer your question? [Binding methods in react components](https://stackoverflow.com/questions/37284795/binding-methods-in-react-components) – Mosia Thabo Apr 18 '20 at 02:01
  • Just remove (), like this {this.getMessage}. Then it will work. But make sure that you have added the constructor as per my answer below. – Mosia Thabo Apr 18 '20 at 02:20
  • `{this.getMessage}` - this has got no meaning – Kid Apr 18 '20 at 02:33
  • two times means prints `hello1` and `hello2`? Or twice `hello2`? Or `hello2`, `hello1`, `hello2`, `hello1`? – Kid Apr 18 '20 at 02:33
  • prints: hello2, hello1, hello2, hello1 – Wilder Salinas Apr 18 '20 at 02:52
  • @O.o it has a meaning, I just didn't realize that he wsn't passing the function to an event where at the end it will be called with `()`... Instead they're just calling it, unattached to an event. {this.getMessage} makes complete sense if you were attaching that function to an event.] – Mosia Thabo Apr 18 '20 at 03:05
  • @MosiaThabo can you get me a codesandbox where you can use like `{this.getMessage}`? – Kid Apr 18 '20 at 03:09
  • Sure simple... add a
    put an onClick = {this.getMessage} and walla! getMessage is executed
    – Mosia Thabo Apr 18 '20 at 03:16

1 Answers1

0

Please check my solution here.

It displays console only once.

(I've removed StrictMode, and works well.)

Kid
  • 1,160
  • 2
  • 14
  • 31
  • Note that StrictMode only causes the double-render in dev. This should not occur in a production build. You can read more here: https://reactjs.org/docs/strict-mode.html The following quote is especially informative: `Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions: Class component constructor, render, and shouldComponentUpdate methods` – jack.benson Apr 18 '20 at 02:48
  • wow, I provided it and if it worked! Thank you. I don't know how it worked, but it worked. thank you very much. – Wilder Salinas Apr 18 '20 at 02:58