The above error occurred in the component

So, I am trying to get a React App up and going. I copied in some HTML from a template into a component. I am running into an error and its not really clear how to handle it. Here is the error. Note

So, I am trying to get a React App up and going. I copied in some HTML from a template into a component. I am running into an error and its not really clear how to handle it. Here is the error. Note there is no error above:

'index.js:1446 The above error occurred in the <div> component:
    in div (at App.js:57)
    in div (at App.js:28)
    in div (at App.js:15)
    in div (at App.js:14)
    in App (at src/index.js:7)

Here is the code that I am placing in App.js:

import React, { Component } from 'react';
import logo from './logo.svg';
import Test from './components/Test.js'
import './App.css';


class App extends Component {
render() {
return (

<React.Fragment>
  <Test />

<div className="probootstrap-hero">
  <div className="container">
    <div className="row">
      <div className="col-md-8 col-md-offset-2 col-sm-8 col-sm-offset-2 text-center probootstrap-hero-text pb0 probootstrap-animate" data-animate-effect="fadeIn">
        <h1>Launch your awesome startup now!</h1>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto provident qui tempore natus quos quibusdam soluta at.</p>
        <p>
          <a href="#" className="btn btn-primary btn-lg" role="button">Get This App</a>
          <a href="#" className="btn btn-primary btn-ghost btn-lg" role="button">Try it for free</a>
        </p>
        <p><a href="#"><i className="icon-play2"></i> Watch the video</a></p> 
       </div>
      </div>
     </div>
    </div>
   
   </React.Fragment>
)}

mikemaccana's user avatar

mikemaccana

103k94 gold badges372 silver badges470 bronze badges

asked Feb 26, 2019 at 11:57

Patrick Bentley's user avatar

Patrick BentleyPatrick Bentley

4321 gold badge4 silver badges17 bronze badges

9

This happens when you use style as a string instead of an object — among less common other reasons like using an object as style and throwing an error in its toString method.

But here is the most reason that such an error is thrown

// the following is JSX and not html
<div style="color:red" />

answered Aug 11, 2020 at 12:54

ehab's user avatar

6

Question:

can’t find way how to resolve this problem.

Errors in browser:

  1. Uncaught Error: Invalid hook call. Hooks can only be called inside
    of the body of a function component. This could happen for one of
    the following reasons:

    • You might have mismatching versions of React and the renderer (such as React DOM)
    • You might be breaking the Rules of Hooks
    • You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to
      debug and fix this problem.
  2. The above error occurred in the component:

    Provider@http://localhost:3000/static/js/bundle.js:49534:15

    Consider adding an error boundary to your tree to customize error
    handling behavior. Visit https://reactjs.org/link/error-boundaries
    to learn more about error boundaries.

INDEX.JS

import React from 'react';
import ReactDOM from 'react-dom';
import Router from './Router';

import { createStore } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import { Provider } from 'react-redux'
import rootReducer from './Redux/Reducers/index.js'


const store = createStore( rootReducer, composeWithDevTools() )

ReactDOM.render(
  <Provider store={ store }>
    <Router />
  </Provider >,
  document.getElementById( 'root' ) );

Reducers/index.js

import loginPageReducer from './LoginPage.js'
import { combineReducers } from 'redux'


const rootReducer = combineReducers( {
   loginPageReducer
} )

export default rootReducer

Reducers/LoginPage.js

const INIT_STATE = {
   view: 'login',
   msg: '',
   loader: false,
}

const loginPageReducer = ( state = INIT_STATE, action ) =>
{

   switch ( action.type )
   {
      case "LOADER_OFF":
         return state.loader = false

      case "LOADER_ON":
         return state.loader = true

      case "MSG_SET":
         return state.msg = action.msg

      case "MSG_CLEAR":
         return state.msg = ''

      case "VIEW_CHANGE":
         return state.view = action.view

      default:
         return state;
   }
}


export default loginPageReducer

loginPage component

import React, { useState } from 'react'
import '../Styles/loginPage.scss'
import axios from 'axios'
import { useDispatch, useSelector } from 'react-redux'
import loginPageActions from '../Redux/actions/LoginPage'

export default function LoginPage () 
{
   const { msg_clear, msg_set, loader_off, loader_on, view_change } = loginPageActions
   const msg = useSelector( state => state.LoginPageReducer.msg )
   const view = useSelector( state => state.LoginPageReducer.view )
   const loader = useSelector( state => state.LoginPageReducer.loader )
   const dispatch = useDispatch()

   const [inputs, setInputs] = useState( {
      username: '',
      password: '',
      password2: '',
      email: ''
   } )

   const handleInputs = function ( e )
   {
      const { name, value } = e.target
      setInputs( { ...inputs, [name]: value } )
   }


   const handleSubmit = async ( e ) =>
   {
      try 
      {
         e.preventDefault();
         dispatch( msg_clear() )
         dispatch( loader_on() )

         if ( view === login)
         {
            // logowanie
            const query = await axios( {
               method: 'post',
               url: '/api/users/login',
               data: {
                  username: inputs.username,
                  password: inputs.password
               }
            } )

            const token = query.data.token
            localStorage.setItem( "token", token );
            return window.location.href = "/kalkulator"

         }
         else
         {
            //rejestracja
            const query = await axios( {
               method: 'post',
               url: '/api/users/register',
               data: {
                  username: inputs.username,
                  password: inputs.password,
                  password2: inputs.password2,
                  email: inputs.email
               }
            } )

            if ( query.status === 200 )
            {
               dispatch( msg_set( 'Zarejestrowano, możesz się zalogować' ) )
               dispatch( view_change( true ) )
            }
         }
      }
      catch ( err ) 
      {
         if ( err ) return dispatch( msg_set( err.response.data.msg ) )
      }
      finally
      {
         dispatch( loader_off() )
      }
   }



   /////////////
   /// Renderowanie widoku
   /////////////


   return (
      <main>
         <div id="MainContainerStyle">
            <span id="thatWhitePartOnBottom"></span>
            <header>
               <h1 id="HeaderH1" >Kalkulator mas</h1>
            </header>



            <button className="Buttons" onClick={ () => dispatch( view_change( !view ) ) }>
               { view ?
                  `Already have account? Click to log in!`
                  :
                  `Doesn't have account? Click me if you want to register new one` }
            </button>


            <form onSubmit={ handleSubmit } id="Form">
               <input type="text"
                  value={ inputs.username }
                  placeholder={ view ? 'username' : 'Login or E-mail' }
                  name="username" required onChange={ handleInputs }
               />

               { view ?
                  <input type="email"
                     placeholder="email"
                     name="email"
                     value={ inputs.email }
                     required
                     onChange={ handleInputs } />
                  :
                  null
               }
               <input type="password"
                  value={ inputs.password }
                  placeholder="Password:"
                  name="password"
                  required
                  onChange={ handleInputs }
               />

               { view ?
                  <input type="password"
                     value={ inputs.password2 }
                     placeholder="Password again:"
                     name="password2"
                     required
                     onChange={ handleInputs } />
                  :
                  null
               }
               <input type="submit" className="Buttons" />

               { loader ? <span className="loader"></span> : null }
               { msg !== '' ? <p className="msg">{ msg }</p> : null }
            </form>
         </div>
      </main>
   )
}

Router

import { BrowserRouter, Routes, Route } from "react-router-dom";
import './Styles/global.scss'

import LoginPage from "./Pages/LoginPage";
import Kalkulator from "./Pages/Kalkulator";

function App ()
{
  return (
    <>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={ <LoginPage /> } />
          <Route path="/kalkulator" element={ <Kalkulator /> } />
        </Routes>
      </BrowserRouter>
    </>
  )
}

export default App;

Answer:

might be this problem: https://reactjs.org/warnings/invalid-hook-call-warning.html#duplicate-react

Assuming myapp and mylib are sibling folders, one possible fix is to run npm link ../myapp/node_modules/react from mylib. This should make the library use the application’s React copy.

..or maybe “react-redux” is not installed, check package.json

If you have better answer, please add a comment about this, thank you!

# #reactjs #firebase-realtime-database #jsx

Вопрос:

Я пытаюсь создать приложение для фотолибрарии с помощью React js. Я сохраняю URL-адрес изображений в базе данных firebase в реальном времени, но когда я пытаюсь отобразить эти изображения с помощью тега img, это выдает ошибку.

 Error: img is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.
 
 The above error occurred in the <img> component:
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
 
 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
 

вот как я получаю URL-адреса из firebase

 componentDidMount(){

    axios.get('/Data.json')
    .then(response => {
       const fetchedData = [];

       for(let key in response.data){
               fetchedData.push({
               ...response.data[key],
               id: key
           });
       }
       this.setState({loading: false, data: fetchedData});
    })

    .catch(error => {
        console.error(error)
        this.setState({loading:false});
    });

}

 

и вот как я пытаюсь отобразить изображения

 this.state.data.reverse().map((res) => (    
        <div className="card1">
                   <Card
                   key={res.id}
                   style={{backgroundColor:"#343a40", textAlign:"left" , 
                   margin:"20px" ,color: "white",
                   left:"370px", borderRadius:"10px",
                   overflow:"hidden", width:"600px", 
                    height:"200px", boxShadow:"0 10px 18px 0 rgba(0,0,0,0.2)"}}
                   >

                  <Card.Body
                  className="container">
                       <h4>
                       ANONYMOUS
                        </h4>
                       <Card.Text>
                        {res.Comment} 
                       </Card.Text>
                        
                        <Card.Img>
                        <img src={res.ImageUrl} width = "400px" height="150px" />
                            </Card.Img>
                 
                 <Button className="btn btn-danger" 
                 style={{float:"right", width:"40px"}}
                 onClick={() => this.DeleteCommentHandler(res.id)}>
                     
                     <FontAwesomeIcon icon={faTrash}/>
                     
                     </Button> 
                   </Card.Body>
                   <Card.Footer>
                       {res.Date}
                   </Card.Footer>
                   </Card>                                
                   
           </div>
       )
)}
 

Пожалуйста, помогите.

Ответ №1:

<Card.Img> является тегом img, поэтому вы должны обновить его, чтобы изменить элемент по умолчанию:

 <Card.Img as="div">
  <img src={res.ImageUrl} width="400px" height="150px" />
</Card.Img>
 

И вы можете добавить переменную для проверки смонтированного или размонтированного компонента перед вызовом setState

 componentDidMount(){
  this.mounted = true;

  ...
  this.mounted amp;amp; this.setState({loading: false, data: fetchedData});
  ...AbortController
}

componentWillUnmount(){
  this.mounted = false
}
 

Содержание

  1. Bug: «The above error…» should appear after the error message but appears before (for some errors) #22656
  2. Comments
  3. Steps To Reproduce
  4. The current behavior
  5. The expected behavior
  6. [Solved] The above error occurred in the
  7. How The above error occurred in the
  8. How To Solve The above error occurred in the
  9. Solution 1: Use this Example
  10. Conclusion
  11. The above error occurred in the component #1225
  12. Comments
  13. Bug Report
  14. The above error occurred in one of React components #15384
  15. Comments
  16. index.stories.tsx

Bug: «The above error…» should appear after the error message but appears before (for some errors) #22656

React version: both latest (17.0.2) and next (18.0.0-alpha-9c8161ba8-20211028)

Steps To Reproduce

  1. Render hello to trigger the «input is a void element tag» error

The current behavior

Two log lines appear:

  1. «The above error occurred in the component»
  2. «input is a void element tag»

The expected behavior

They should be in the other order:

  1. «input is a void element tag»
  2. «The above error occurred in the component»

This problem doesn’t occur in the same way if a component throws an error. Presumably this goes through a different error handling path because it comes from the host config.

If someone works on this, you may also want to review look at this issue at the same time:

The text was updated successfully, but these errors were encountered:

The input tag should not have any children. Instead of this you should use input and label tag if you want to write text out of input area.

Hi @aniler0 – I’m aware. 🙂 But when someone makes this mistake, the reporting of the error should be a little different than it is today, and that’s what this bug is about.

When using style as a string instead of an object, the error doesn’t show at all. Is only this message:

(this is caused by something like

@Berci-Ionut I can’t reproduce that. For me it does show the error:

If you can reproduce this in a standalone code sandbox, do feel free to link it here though.

Hmm. Seems like is only reproducing when using NextJS (example here) . In this case I am not sure if the issue is related to react or rather NextJS
EDIT: it seems like a forked nextJS link is failing on sandbox for some reason (at least for me). But if you create a new NextJS sandbox and paste the code it will be reproduced.

Still relevant (just verified in 18.0.0 stable) – this and #18101 are both interesting IMO.

Hi @sophiebits, I would like to work on this issue.

Sure, please feel free to. The first step would be to investigate why this is happening and post a comment here explaining the difference in behavior. Then we can look at the implementation.

The input tag should be a self closing tag

@sylvesterAdewale This is not what the issue is about. The issue is about the ordering of the messages. @sophiebits already responded to this in #22656 (comment).

Oops. I have worked for a while on the issue. I guess I understand why messages are ordering like that. But I didn’t know issues can be take.

Hi @MustafaEminn, If you already have worked on this issue then you can surely write a patch for this, I will try to learn from your patch.

We can’t run console methods after throwing the error. «The above error occurred. » error is logging by console.error method and the second error «. is a void element. » is throw a new error. If I want to tell in order.
assertValidProps method throw an error —> renderRootSync catch the error —> commitUpdateQueue call callCallback method and print the first error using console.error. Also, this callback set hasUncaughtError variable to true. —> commitRootImpl works again and throws an error which is «. is a void element. » error.

What is the solution?
I guess changing the above word to below will be good. Because we can’t run console methods after throwing the error. I already changed and tested with yarn test. There is no failure.

If we want to log both of these errors, we can’t interrupt the execution without throwing another error.

Источник

[Solved] The above error occurred in the

I am trying to run my reactjs Code But I am facing the following error and Facing some errors with the div: The above error occurred in the
component
in ReactJS. In this Exerror article, We are going to learn about How to reproduce this error and we will discuss All Possible Solutions Lets Get Start with This Article.

How The above error occurred in the

I am trying to run my reactjs Code But I am facing the following error and Facing some errors with the div:

So here I am writing all the possible solutions I have tried to resolve this error.

How To Solve The above error occurred in the

  1. How To Solve The above error occurred in the

The Most Common Reason for this error is You are using style as a string in your Div element. You cant use style like style=”color:red” if You want to use the style in your div then you can use the style like below: div style=<> And Now, Your error must be solved. Thank You.

The Most Common Reason for this error is You are using style as a string in your Div element. You cant use style like style=”color:red” if You want to use the style in your div then you can use the style like below: div style=<> And Now, Your error must be solved. Thank You.

Solution 1: Use this Example

The most Common Reason for this error is You are using style as a string in your Div element. You cant use style like style=”color:red” if You want to use style in your div then you can use style like below.

And Now, Your error must be solved. Thank You.

Conclusion

It’s all About this error. I hope We Have solved Your error. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?

Источник

The above error occurred in the component #1225

Bug Report

The error occur when I npm run dev.
Go wrong in 2.0.0-rc.68, but not happen in 1.3.2.

The text was updated successfully, but these errors were encountered:

Could you please provide more information and the whole error that was printed ?

ok,
Like I said, I try to upgrade docz’s version from 1.3.2 to 2.0.0-rc.68,
and the error occur as below, which doesn’t happen in 1.3.2.

command: npm run dev

node version: v10.15.3
npm version: 6.4.1
related plugins version:

Could you try uninstalling docz-theme-default :

Have tried, but doesn’t work. 😂
Same error.

Then I’m not sure what the problem is based on the information you provided.

If you could try to provide a repo with a repro of the problem that would be great.

I just created a repo.
repo

Then the problem show.Please check if can help.

Thanks for providing a repro !

I see you’re using docz-plugin-css to parse postcss code.

Starting from v2 you don’t need this plugin, you can rely on a GatsbyJS plugin to take care of that :

  1. Remove docz-plugin-css : yarn remove docz-plugin-css
  2. Remove docz-plugin-css from doczrc.js plugins:
  1. Add gatsby-plugin-postcss : yarn add gatsby-plugin-postcss
  2. Add a config ( gatsby-config.js ) to tell Gatsby to use this plugin :
  1. Add a postcss config if you don’t have one in your project

After doing these steps your provided repo works as expected.

Thanks!
It works!

But it seems I have to use yarn .

At first, I use npm install , and the same problem occur.
Then I use yarn , it works.

I’m having the exact same issue. I’m not using any additional docz plugins, though.
Basically, I have this:

I’m running docz as ./node_modules/.bin/docz dev

I have this output:

Could you provide a repro repo ?

Or failing that :

  • your complete package.json
  • the mdx file you’re trying to render
  • The JS/TS you’re using in your mdx

@rakannimer
Yep. I concluded that the error happens in the project that was generated by create-react-app .
Here’s the reproduction repository: https://github.com/everdimension/docz-repro

I also tried to use docz in a project created from scratch, it worked fine. So I guess there are some conflicts with the libs used by create-react-app .

Using yarn instead of npm i solved the issue.

@chhuang Interestingly, it solves the issue for me, too, if I remove node_modules and reinstall them with yarn

But I believe that docz should of course support both npm and yarn .

I guess we should find out what exactly leads to this inconsistency. Perhaps docz depends on some package that has yarn-specific behavior.

The app itself works fine with npm .

Same error with docz@2.0.0-rc.73 and npm

version ^2.0.0-rc.55 doesn’t have this problem with npm.

@crusoexia did you delete your node_modules directory first? I tried that version and still ran into the same issues, I had to make use of yarn

@kinsomicrote for 2.0.0-rc.55, it worked after I remove the entire node_modules and reinstall with npm. For 2.0.0-rc.73, it never worked for whatever way I tried.

Thanks for sharing, had to revert to version 1.3.2 to get it to work.

Is it possible that this related to this which happens with gatsby?

I ran into this same issue and as @kinsomicrote mentioned it seemed to be related to the Gatsby issue. Removing node_modules , yarn-lock and reinstalling with yarn fixed it for me.

@chhuang Interestingly, it solves the issue for me, too, if I remove node_modules and reinstall them with yarn

But I believe that docz should of course support both npm and yarn .

I guess we should find out what exactly leads to this inconsistency. Perhaps docz depends on some package that has yarn-specific behavior.

The app itself works fine with npm .

Thanks! this worked for me

how can I get this working with npm. It’s not possible for me to migrate to yarn right now

Removing node_modules & package.lock and installing it with yarn worked for me aswell. Really weird, does anyone know what would cause it to work with yarn but not npm?

having this problem with docz 2.2.0, is there a work around using npm. can not switch to yarn currently

With npm upgrading react and react-dom to 16.12.0 and reinstalling node_modules fixed the problem for me

Thanks @nkicinska, that worked for me too.

damn, so weird that deleting node_modules and switching to yarn only fixes it,
this is the sort of issues I hate, infrastructure/tooling stack issues that are hard to trace the cause of, it could be npm caching or anything else.
and what was the cause? upgrading a package by bumping up a version in package.json and npm i ing.

here is the full output:

PS: I’m using only Gatsby, not docz.

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

It works if I using yarn but using npm it failed to build

Encountered too many times of this issue whenever have a massive upgrade of dependencies, especially in monorepo, so post the tips here that I solve this issue which every time I would forget:

Источник

The above error occurred in one of React components #15384

I have updated Storybook to version 6.3.0 I got a weird error in the browser console, but no errors in the IDE console

These components are not in our project, most likely they are inside the storybook

«addons»: [
«@storybook/addon-docs»,
«@storybook/addon-links»,
«@storybook/addon-essentials»,
«@storybook/addon-actions»,
«@storybook/addon-backgrounds»,
«@storybook/addon-knobs»,
«@storybook/addon-viewport»,
«storybook-addon-designs»,
«storybook-addon-i18next»,
«@storybook/addon-postcss»,
]

System
OS: macOS 11.3
CPU: (8) arm64 Apple 2019 core i 9
Binaries:
Node: 12.16.2
yarn: 1.22.5
Browsers:
Chrome: 90.0.4430.212
Firefox: 88.0.1
Safari: 14.1.1

The text was updated successfully, but these errors were encountered:

Without any actual repro it will be hard to debug what is happening. Can you run and paste the results of npx sb@next info ? Did it work with previous storybook integrations? Does any warning appear in the storybook build? How are the stories written?
Also, would this ticket close #15098?

const path = require(‘path’);

module.exports = <
«stories»: [
«../stories//*.stories.mdx»,
«../stories/
/*.stories.@(js|jsx|ts|tsx)»
],
«addons»: [
«@storybook/addon-docs»,
«@storybook/addon-links»,
«@storybook/addon-essentials»,
«@storybook/addon-actions»,
«@storybook/addon-backgrounds»,
«@storybook/addon-knobs»,
«@storybook/addon-viewport»,
«storybook-addon-designs»,
«storybook-addon-i18next»,
<
name: ‘@storybook/addon-postcss’,
options: <
postcssLoaderOptions: <
implementation: require(‘postcss’),
>
>
>
],
webpackFinal: async (config, < configType >) => <
// configType has a value of ‘DEVELOPMENT’ or ‘PRODUCTION’
// You can change the configuration based on that.
// ‘PRODUCTION’ is used when building the static version of storybook.

index.stories.tsx

import React from ‘react’;

import < Story, Meta >from ‘@storybook/react’;

import RadioButton, < RadioButtonProps >from ‘app/design-system/components/RadioButton’;

import < LabelSize >from ‘app/design-system/types/Label’;

import StoryContainer, < SANDBOX_WIDTH_OPTIONS >from ‘../../../helpers/StoryContainer’;

export default <
title: ‘Дизайн-система / Атомы / РадиоКнопка’,
component: RadioButton,
argTypes: <
labelSize: <
defaultValue: LabelSize.DEFAULT,
control: <
type: ‘select’,
options: LabelSize,
>,
>,
label: <
name: ‘текст РадиоКнопки’,
>,
disabled: <
defaultValue: false,
control: <
type: ‘boolean’,
>,
>,
checked: <
defaultValue: false,
control: <
type: ‘boolean’,
>,
>,
onChange: <
table: <
disable: true,
>,
action: ‘changed’,
>,
>,
> as Meta;

const Sandbox: Story = (args) => (

);

Источник

Когда попытался сделать рефакторинг кода, вывести повторяющие значение во функцию, то получаю ошибку

The above error occurred in the <Lesson> component:
    in Lesson (created by Calendar)
    in tr (created by Calendar)
    in tbody (created by Calendar)
    in table (created by Calendar)
    in div (created by Calendar)
    in Calendar

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://fb.me/react-error-boundaries to learn more about error boundaries.

Uncaught Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://fb.me/react-crossorigin-error for more information.
    at Object.invokeGuardedCallbackDev (react-dom.development.js:626)
    at invokeGuardedCallback (react-dom.development.js:476)
    at renderRoot (react-dom.development.js:10908)
    at performWorkOnRoot (react-dom.development.js:11556)
    at performWork (react-dom.development.js:11509)
    at requestWork (react-dom.development.js:11420)
    at scheduleWorkImpl (react-dom.development.js:11274)
    at scheduleWork (react-dom.development.js:11231)
    at scheduleTopLevelUpdate (react-dom.development.js:11735)
    at Object.updateContainer (react-dom.development.js:11773)

Действия по воспроизведению

  1. Рендеринг <input>hello</input>для запуска ошибки «input is the void element tag»

Ссылка на пример кода: https://codesandbox.io/s/cocky-matan-ydmys

Текущее поведение

Появляются две строки журнала:

  1. “Вышеупомянутая ошибка произошла в компоненте <input>”
  2. “input является пустым тегом элемента”

изображение

Ожидаемое поведение

Они должны быть в другом порядке:

  1. “input является пустым тегом элемента”
  2. “Вышеупомянутая ошибка произошла в компоненте <input>”

Эта проблема не возникает таким же образом, если компонент выдает ошибку. Предположительно, это происходит через другой путь обработки ошибок, потому что он исходит из конфигурации хоста.

 прошлом ошибки JavaScript внутри компонентов искажали внутреннее состояние React и заставляли его выдавать загадочные ошибки при следующем рендеринге. Эти ошибки всегда были вызваны более ранней ошибкой в ​​коде приложения, но React не предоставлял способ изящной обработки их в компонентах и ​​не мог восстановиться после них.

Введение границ ошибок

Ошибка JavaScript в части пользовательского интерфейса не должна нарушать работу всего приложения. Чтобы решить эту проблему для пользователей React, React 16 вводит новую концепцию «границы ошибки».

Границы ошибок — это компоненты React, которые перехватывают ошибки JavaScript в любом месте своего дерева дочерних компонентов, регистрируют эти ошибки и отображают резервный пользовательский интерфейс вместо дерева компонентов, в котором произошел сбой. Границы ошибок перехватывают ошибки во время рендеринга, в методах жизненного цикла и в конструкторах всего дерева под ними.

Примечание

Границы ошибок не перехватывают ошибки для:

  • Обработчики событий ( узнать больше )
  • Асинхронный код (например , setTimeoutили requestAnimationFrameобратные вызовы)
  • Рендеринг на стороне сервера
  • Ошибки, возникающие в самой границе ошибки (а не в ее дочерних элементах)

Компонент класса становится границей ошибки, если он определяет один (или оба) из методов жизненного цикла static getDerivedStateFromError()или componentDidCatch(). Используется static getDerivedStateFromError()для отрисовки резервного пользовательского интерфейса после возникновения ошибки. Используйте componentDidCatch()для регистрации информации об ошибках.

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 };  }
  componentDidCatch(error, errorInfo) {    // You can also log the error to an error reporting service    logErrorToMyService(error, errorInfo);  }
  render() {
    if (this.state.hasError) {      // You can render any custom fallback UI      return <h1>Something went wrong.</h1>;    }
    return this.props.children; 
  }
}

Затем вы можете использовать его как обычный компонент:

<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>

Границы ошибок работают как catch {}блок JavaScript, но для компонентов. Только компоненты класса могут быть границами ошибки. На практике в большинстве случаев вам потребуется один раз объявить компонент границы ошибки и использовать его во всем приложении.

Обратите внимание, что границы ошибок улавливают ошибки только в компонентах, расположенных ниже них в дереве . Граница ошибки не может поймать ошибку внутри себя. Если границе ошибки не удается отобразить сообщение об ошибке, ошибка будет распространяться на ближайшую границу ошибки над ней. Это тоже похоже на то, как catch {}блок работает в JavaScript.

Понравилась статья? Поделить с друзьями:
  • That name is already taken minecraft как исправить
  • The error code reported is enotimplementedyet 3d max
  • That means stock recovery installation failed unknown error
  • The emulator process for avd has terminated андроид студио как исправить
  • That kit is improperly defined contact an administrator как исправить