What would the same code look like in Reactjs using Hook to rescue the start of component creation?

Asked

Viewed 25 times

1

With the code just below I want to simulate the same effect with React Hook in the componentWillMount method contained in classes for ?

Example below with code:

class Example extends React.Component {
  constructor() {
    super();
    this.state = {
      count: 0
    }
    this.handleIncrement
      = this.handleIncrement.bind(this);
  }
  componentWillMount(){
    console.log('Component InitMount');
  }  
  handleIncrement() {
    let { count }  = this.state;
    count = count + 1;
    this.setState({count});
  }
  render() {
    return (
      <div>
        <div>{this.state.count}</div>
        <div><button onClick={this.handleIncrement}>Incremento</button></div>
      </div>
    );
  }
}
ReactDOM.render(<Example/>, document.getElementById('root'));
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root">Aguarde ...</div>

1 answer

1


To have the same effect use the useEffect with a array without any item, as an example below:

function Example() {
  const [count, setCount] = React.useState(0);
  const handleIncrement = () => setCount(count + 1);
  React.useEffect(() => {
    console.log('Component InitMount');
  }, []);
  return (
  <div>
    <div>{count}</div>
    <div>
      <button onClick={handleIncrement}>Incremento</button>
    </div>
  </div>);
}

ReactDOM.render(<Example/>, document.getElementById('root'));
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
<div id="root">Aguarde ...</div>

Reference: https://stackoverflow.com/questions/53464595/how-to-use-componentwillmount-in-react-hooks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.