mercredi 23 juin 2021

React.JS TypeError: Cannot read property 'number' of undefined - (inside setState)

Hello everyone,
In my ReactJS website I get this error - `TypeError: Cannot read property 'number' of undefined`
`HTMLInputElement.anonymous ` why ?

I did console.log(this.state.number) and number has a value in it.

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mobileNum: '',
      number: '',
    };
  }  

  somefunction=()=>{ // Called with onKeyDown 
    this.setState({ number: document.getElementById('mySubmit').value });

  
  enterPressed = () => {
    const submit = document.getElementById('mySubmit');
    submit.addEventListener('keyup', function (event) {
      if (event.key === 'Enter') {
        this.setState({ mobileNum: this.state.number }); // Here is the error line !
      }
    });
  };

If I use setState with if condition in another function it will do error - setState is not a function
this.setState({ mobileNum: this.state.number }) is working also in a different fuction I made, but in enterPressed() isn't.


Thanks for the helpers :)

Aucun commentaire:

Enregistrer un commentaire