Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
Con React ErrorBoundary, quiero restablecer hasError desde una función interna

No soy tan bueno en las clases de JavaScript (ya que uso componentes funcionales casi exclusivamente). Tengo una clase ErrorBoundary ligeramente modificada que en su mayoría pegué de los documentos de React.

Tengo un código que usa este ErrorBoundary al que puedo llamar correctamente al método resetError que he definido en addExtraProps . Quiero restablecer "this.state.error" a falso desde esta función. Creo que es una cosa de JavaScript, nada que ver con React.

Puede ver que he comentado this.setState({ hasError: false }) ya que eso no funciona porque la función externa que llama a esto no tiene acceso a this (supongo).

Agradezco cualquier ayuda.

 class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { // Update state so the next render will show the fallback UI. return { hasError: true, message: error?.message, status: error?.status }; } render() { function addExtraProps(Component, extraProps) { return ( <Component.type {...Component.props} resetError={() => { debugger; // THE BELOW CODE DOES NOT WORK AS WE DON'T HAVE ACCESS TO // "THIS" IN A CALL FROM AN EXTERNAL FUNCTION. // //this.setState({ hasError: false }); }} {...extraProps} /> ); } if (this.state.hasError) { return addExtraProps(this.props.fallback, { errorMessage: this.state.message, errorStatus: this.state.status, }); } return this.props.children; } }

Además, aunque hay mucho en el medio, así es como se ve la llamada que ejecuta resetError :

 function ErrorBoundaryFallback({ errorMessage, errorStatus, resetError }) { return ( <> <hr /> <div className="city-details"> <div> <b>Error:</b> {errorMessage} {" ..... "} <b>Status:</b> {errorStatus} </div> </div> <button onClick={() => resetError()}>Try again with resetError</button> </> ); }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

 class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; //----- this is what i meant by binding in the constructor this.changeState = this.changeState.bind(this) } //----- this is the new method changeState() { this.setState({ hasError: false }); } static getDerivedStateFromError(error) { // Update state so the next render will show the fallback UI. return { hasError: true, message: error?.message, status: error?.status }; } render() { function addExtraProps(Component, extraProps) { return ( <Component.type {...Component.props} resetError={this.changeState} {...extraProps} /> ); } if (this.state.hasError) { return addExtraProps(this.props.fallback, { errorMessage: this.state.message, errorStatus: this.state.status, }); } return this.props.children; } }

about 4 years ago · Juan Pablo Isaza Report

0

El problema radica en la parte donde creas function addExtraProps . Esa función rompe su entrada a this desde la clase ErrorBoundry .

Necesitas crear esa función como flecha, y estarás bien.

 class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { // Update state so the next render will show the fallback UI. return { hasError: true, message: error?.message, status: error?.status }; } render() { const addExtraProps = (Component, extraProps) => { return ( <Component.type {...Component.props} resetError={() => { this.setState({ hasError: false }); }} {...extraProps} /> ); } if (this.state.hasError) { return addExtraProps(this.props.fallback, { errorMessage: this.state.message, errorStatus: this.state.status, }); } return this.props.children; } }

En el otro caso, puede extraer esa lógica setState en un método de su clase y configurarla allí, y luego asignarla a esa devolución de llamada resetError :

 class ErrorBoundary extends React.Component { // ... resetError = () => { this.setState({ hasError: false}); } render() { const addExtraProps = (Component, extraProps) => { return ( <Component.type {...Component.props} resetError={resetError} {...extraProps} /> ); } // ... } }

Sugeriría usar siempre la función de flecha cuando se trata de clases.

Aquí puede ver un ejemplo de método de flecha donde asigno valor al método de clase resetError como función de flecha. No es necesario hacer this.resetError.bind(this) en el constructor. Esa era la manera antigua.

Si solo usa JS simple (sin TypeScript), posiblemente necesite agregar este complemento de babel para poder usar métodos de flecha. (tal vez esté incluido en las versiones más nuevas de babel, lo usé hace mucho tiempo)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!