Counter does not update data on the page using Reactjs and useState(), only when I place a console.log() can I see the result

Asked

Viewed 387 times

0

I’m taking a Reactjs course, and I’m trying to follow all the code examples, but my code is the same as the instructor’s and yet mine is not working the same as his. Every time you click increment, it is called a function to realize a basic account and uses useState to update the array value, but even so on my screen in the browser when clicking the button continues without updating and if I put a console.log() i can see that with each click on the button the value adds 1 more.

import React, {useState} from 'react'
import Header from './Header'

function App() {
  const [count, setCounter] = useState(0)

  function increment() {
    setCounter(count + 1);
    console.log(count)
  }

  return (
    <div>
       <Header>Contador: {count}</Header>
       <button onClick={increment}>Incrementar</button>
    </div>
  )
}

export default App

print do código e do resultado

  • 3

    You can show your <Header>? Your code works for me... https://jsfiddle.net/j81Le92q/

1 answer

0

We are not absolutely sure, but for his problem presented missed catch children of his props in the component <Header />, to render any functionality being these functions javascript, text and objects. An example that solves the problem of not displaying the value is the following:

function Header(props) {
  return (
    <div>{props.children}</div> // children
  )
}
function App() {
  const [count, setCounter] = React.useState(0);

  function increment() {
    setCounter(count + 1);
  }

  return (
    <div>
       <Header>Contador: {count}</Header>
       <button onClick={increment}>Incrementar</button>
    </div>
  )
}

ReactDOM.render(<App/> , 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>

References:

Browser other questions tagged

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