Program Club

React.createElement : 유형이 잘못되었습니다. 문자열이 필요합니다.

proclub 2020. 11. 21. 08:56
반응형

React.createElement : 유형이 잘못되었습니다. 문자열이 필요합니다.


react-router (v4.0.0)와 react-hot-loader (3.0.0-beta.6)가 멋지게 재생되도록 시도했지만 브라우저 콘솔에서 다음 오류가 발생합니다.

경고 : React.createElement : 유형이 유효하지 않습니다. 문자열 (내장 구성 요소의 경우) 또는 클래스 / 함수 (복합 구성 요소의 경우)가 예상되지만 정의되지 않았습니다. 정의 된 파일에서 구성 요소를 내보내는 것을 잊었을 수 있습니다.

index.js :

import React from 'react';
import ReactDom from 'react-dom';
import routes from './routes.js';
require('jquery');
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.min.js';
import './css/main.css';

const renderApp = (appRoutes) => {
    ReactDom.render(appRoutes, document.getElementById('root'));
};

renderApp( routes() );

route.js :

import React from 'react';
import { AppContainer } from 'react-hot-loader';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import store from './store/store.js';
import { Provider } from 'react-redux';
import App from './containers/App.jsx';
import Products from './containers/shop/Products.jsx';
import Basket from './containers/shop/Basket.jsx';

const routes = () => (

    <AppContainer>
        <Provider store={store}>
            <Router history={browserHistory}>
                <Route path="/" component={App}>
                    <IndexRoute component={Products} />
                    <Route path="/basket" component={Basket} />
                </Route>
            </Router>
        </Provider>
    </AppContainer>

);

export default routes;

대부분의 경우 올바르게 내보내거나 가져 오지 않았기 때문입니다.

일반적인 오류 :

// File: LeComponent.js
export class LeComponent extends React.Component { ... }

// File: App.js
import LeComponent from './LeComponent';

// no "default" export, should be  export default class LeComponent

몇 가지 방법이 틀릴 수 있지만 그 오류는 매번 60 %의 수입 / 수출 실수로 인한 것입니다.

편집하다

일반적으로 당신은 해야 실패가 발생하는 위치의 대략적인 위치를 나타내는 스택 트레이스를 얻을. 이것은 일반적으로 원래 질문에있는 메시지 바로 다음에 이어집니다.

표시되지 않으면 이유를 조사해 볼 가치가 있습니다 (누락 된 빌드 설정일 수 있음). 그럼에도 불구하고 표시되지 않는 경우 유일한 조치는 내보내기 / 가져 오기가 실패한 위치를 좁히는 것 입니다.

슬프게도 스택 추적없이이를 수행하는 유일한 방법은 더 이상 오류가 발생하지 않을 때까지 각 모듈 / 하위 모듈을 수동으로 제거한 다음 스택을 백업하는 것입니다.

편집 2

주석을 통해 실제로 존재하지 않는 모듈을 가져 오는 것은 실제로 가져 오기 문제였습니다.


이 시도

npm i react-router-dom@next

당신의 App.js

import { BrowserRouter as Router, Route } from 'react-router-dom'

const Home = () => <h1>Home</h1>

const App = () =>(
  <Router>
    <Route path="/" component={Home} />
  </Router>
)

export default App;

이 오류도 발생했습니다.

나는 사용하고 있었다 :

import BrowserRouter from 'react-router-dom';

대신 다음과 같이 수정했습니다.

import { BrowserRouter } from 'react-router-dom';


구성 요소 파일과 동일한 폴더에 css 파일을 추가 할 때이 문제가 발생했습니다.

내 수입 명세서는 다음과 같습니다.

import MyComponent from '../MyComponent'

MyComponent.jsx라는 단일 파일 만 있으면 괜찮 았습니다. (예제에서이 형식을보고 시도해 본 다음 수행 한 것을 잊었습니다)

MyComponent.scss를 같은 폴더에 추가했을 때 가져 오기가 실패했습니다. JavaScript가 대신 .scss 파일을로드했기 때문에 오류가 없었을 수 있습니다.

내 결론 : 나중에 다른 파일을 추가 할 경우 파일이 하나만 있더라도 항상 파일 확장자를 지정하십시오.


향후 Google 사용자를 위해 :

이 문제에 대한 내 솔루션 업그레이드했다 reactreact-domNPM에 최신 버전에. 분명히 새 조각 구문을 사용하는 구성 요소를 가져오고 있었고 이전 버전의 React에서 손상되었습니다.


나를 위해 놓친 것은 내가 사용하고 있었다

import { Router, Route, browserHistory, IndexRoute } from 'react-router';

대신 또는 정답은 다음과 같아야합니다.

import { BrowserRouter as Router, Route } from 'react-router-dom';

물론 npm 패키지 react-router-dom 을 추가해야합니다 .

npm install react-router-dom@next --save

named export및을 알고 있어야 default export합니다. ES6 가져 오기에 언제 중괄호를 사용해야합니까?를 참조하십시오 .

제 경우에는

import Provider from 'react-redux'

...에

import { Provider } from 'react-redux'

이 문제는 render / return 문에 잘못된 참조가있을 때 발생했습니다. (존재하지 않는 클래스를 가리킴). 또한 반환 문 코드에서 잘못된 참조를 확인하십시오.


제 경우에는 구성 요소를 만들고 렌더링하는 순서가 중요했습니다. 구성 요소를 만들기 전에 렌더링했습니다. 가장 좋은 방법은 자식 구성 요소를 만든 다음 부모 구성 요소를 만든 다음 부모 구성 요소를 렌더링하는 것입니다. 주문을 변경하면 문제가 해결되었습니다.


제 경우에는 그냥 업그레이드했다 react-router-reduxreact-router-redux@next. 나는 그것이 일종의 호환성 문제라고 가정하고 있습니다.


이 오류가 발생하고 응답이 내 경우가 아니므로 누군가 인터넷 검색에 도움이 될 수 있습니다.

Proptype을 잘못 정의했습니다.

ids: PropTypes.array(PropTypes.string)

그것은해야한다:

ids: PropTypes.arrayOf(PropTypes.string)

VSCode 및 컴파일 오류로 인해 올바른 힌트가 제공되지 않았습니다.


간단히 말해서, 어떻게 든 다음과 같은 일이 발생합니다.

render() {
    return (
        <MyComponent /> // MyComponent is undefined.
    );
}

잘못된 가져 오기 또는 내보내기와 반드시 관련이있는 것은 아닙니다.

render() {
    // MyComponent may be undefined here, for example.
    const MyComponent = this.wizards[this.currentStep];

    return (
        <MyComponent />
    );
}

구성 요소를 테스트 할 때이 오류가 발생하면 모든 자식 구성 요소가 단독으로 실행될 때 올바르게 렌더링되는지 확인하고, 자식 구성 요소 중 하나가 렌더링 할 외부 리소스에 의존하는 경우 jest 또는 다른 모의 lib를 사용하여 조롱 해보십시오.

예 :

jest.mock('pathToChildComponent', () => 'mock-child-component')

Most of the time this indicates an import/export error. But be careful to not only make sure the referenced file in the stack trace is well exported itself, but also that this file is importing other components correctly. In my case the error was like this:

import React from 'react';

// Note the .css at the end, this is the cause of the error!
import SeeminglyUnimportantComponent from './SeeminglyUnimportantComponent.css';

const component = (props) => (            
  <div>
    <SeeminglyUnimportantComponent />
    {/* ... component code here */}
  </div>    
);

export default component;


In my case, the error occurred when trying to use ContextApi. I have mistakenly used:

const MyContext = () => createContext()

But it should have been defined as:

const MyContext = createContext()

I am posting it here so that future visitors who get stuck on such a silly mistake will get it helpful to avoid hours of headache, coz this is not caused by incorrect import/export.


I think the most important thing to realize when troubleshooting this bug is that it manifests when you attempt to instantiate a component that doesn't exist. This component doesn't have to be imported. In my case I was passing components as properties. I forgot to update one of the calls to properly pass the component after some refactoring. Unfortunately, since JS isn't statically typed my bug wasn't caught, and it took some time to figure out what was happening.

To troubleshoot this bug inspect the component before you render it, to make sure that it's the type of component you expect.


EDIT

You are complexifying the process. Just do this :

index.js:

import React from 'react';
import ReactDom from 'react-dom';
import routes from './routes.js';
require('jquery');
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.min.js';
import './css/main.css';

ReactDom.render(<routes />, document.getElementById('root'));

routes.js:

import React from 'react';
import { AppContainer } from 'react-hot-loader';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import store from './store/store.js';
import { Provider } from 'react-redux';
import App from './containers/App.jsx';
import Products from './containers/shop/Products.jsx';
import Basket from './containers/shop/Basket.jsx';

const routes =
    <AppContainer>
        <Provider store={store}>
            <Router history={browserHistory}>
                <Route path="/" component={App}>
                    <IndexRoute component={Products} />
                    <Route path="/basket" component={Basket} />
                </Route>
            </Router>
        </Provider>
    </AppContainer>;

export default routes;

I just spent 30 minutes trying to solve this BASIC basic issue.

My problem was I was importing react native elements

eg import React, { Text, Image, Component } from 'react';

And trying to use them, which caused me to receive this error.

Once I switch from <Text> to <p> and <Image> to <img> everything worked as expected.

참고URL : https://stackoverflow.com/questions/42813342/react-createelement-type-is-invalid-expected-a-string

반응형