Home > Back-end >  Component isn't updated and I don't really understand why
Component isn't updated and I don't really understand why

Time:10-05

I've just began learning React and I want to create a button which generates a random number.

For some reason though, the DOM is not updated with the new value when I click on the button.

Here is the code:

import logo from './logo.svg';
import './App.css';
import React from 'react';
import PropTypes from 'prop-types';

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      number: 0
    }

    this.generateRandomNumber = this.generateRandomNumber.bind(this);
  }

  generateRandomNumber() {
    this.setState = {
      number: Math.random()
    }
  }
  render() { 
    return (  
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
      </header>
      <button onClick={this.generateRandomNumber}>random</button>
      <Number myNumber={this.state.number}/>
    </div>
  );
  }

}

class Number extends React.Component {
  render() { 
    return <div className="Number">{this.props.myNumber}</div>;
  }
}
  
export default App;

I just press the random button and nothing happens.

CodePudding user response:

  this.setState = {
      number: Math.random()
    }

You should not update state this way. You need to call setState.

this.setState({number: Math.random()});

More info.

CodePudding user response:

setState is a function

this.setState({ number: Math.random() })

  • Related