Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

209
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda