Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

150
Visualizações
Event handlers, render and other methods binding in React

Why do event handlers need to bind with the constructor while render and other methods do not require the same in react?

You may see here in the below code that for handlesubmit I need to bind it with the constructor but I don't need to do the same with api method. Can someone explain to me the reason behind it?

Thank you

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

  this.state={
    users:[],
    loading:false
  };
  this.handleSubmit = this.handleSubmit.bind(this); 
}

api(){ 
  this.setState({
    loading: true
  }) 
    axios('https://api.randomuser.me/')
  .then(respond => this.setState({ 
    users: [...this.state.users, ...respond.data.results], 
    loading: false
  }))
}
handleSubmit(e){ 
  e.preventDefault(); 
  this.api();
}

UNSAFE_componentWillMount(){
this.api();
}

render(){
let {loading,users} = this.state; 
console.log("run")
return <div className = "App"> 
 <form onSubmit = {this.handleSubmit}> 
  <input type="submit" value= "Refresh" /> 
  </form>
{!loading 
  ? (users.map( user => 
  <div key = {user.id.value}> 
  <h2> {user.name.first} </h2>
  <p>{user.email}</p>
  </div>
)) : (<Loading/>)} 
</div>;
}
}

export default App;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

So that their references don't change on each re-render.

  this.handleSubmit = this.handleSubmit.bind(this); 

You can just use arrow function

handleSubmit = (e) => { 
  e.preventDefault(); 
  this.api();
}

why do you need to bind a function in a constructor

See more https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

https://www.freecodecamp.org/news/this-is-why-we-need-to-bind-event-handlers-in-class-components-in-react-f7ea1a6f93eb/

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda