program tip

React 프로젝트에서“클래스를 함수로 호출 할 수 없습니다”얻기

radiobox 2020. 8. 6. 08:12
반응형

React 프로젝트에서“클래스를 함수로 호출 할 수 없습니다”얻기


프로젝트에 React 맵 구성 요소를 추가하려고하는데 오류가 발생합니다. Fullstack React의 블로그 게시물 을 참조로 사용하고 있습니다. google_map.js 줄 83에서 오류가 발생하는 위치를 추적했습니다.

function _classCallCheck(instance, Constructor) { 
  if (!(instance instanceof Constructor)) { 
    throw new TypeError("Cannot call a class as a function"); 
    } 
  }

여기 내지도 구성 요소가 있습니다. 마지막 세 줄인 58-60 줄을 주석 처리하면 페이지가 맵없이 잘로드됩니다. 편집 : @Dmitriy Nevzorov가 제안한 변경 사항을 적용했지만 여전히 동일한 오류가 발생합니다.

import React from 'react'
import GoogleApiComponent from 'google-map-react'

export class LocationsContainer extends React.Component {
    constructor() {
        super()
    }
  render() {
    const style = {
        width: '100vw',
        height: '100vh'
    }
    return (
      <div style={style}>
        <Map google={this.props.google} />
      </div>
    )
  }
}

export class Map extends React.Component {
    componentDidUpdate(prevProps, prevState){
        if (prevProps.google !== this.props.google){
            this.loadMap();
        }
    }
    componentDidMount(){
        this.loadMap();
    }
    loadMap(){
        if (this.props && this.props.google){
            const {google} = this.props;
            const maps = google.maps;

            const mapRef = this.refs.map;
            const node = ReactDOM.findDOMNode(mapRef);

            let zoom = 14;
            let lat = 37.774929
            let lng = 122.419416
            const center = new maps.LatLng(lat, lng);
            const mapConfig = Object.assign({}, {
                center: center,
                zoom: zoom
            })
            this.map = new maps.Map(node, mapConfig)
        }
    }
    render() {
        return (
            <div ref='map'>
                Loading map...
            </div>
        )
    }
}

export default GoogleApiComponent({
  apiKey: MY_API_KEY
})(LocationsContainer)

그리고이지도 구성 요소가 main.js에서 라우팅되는 위치는 다음과 같습니다.

import {render} from 'react-dom';
import React from 'react';
import Artists from './components/Artists'
import { Router, Route, Link, browserHistory } from 'react-router'
import Home from './components/HomePage'
import Gallery from './components/ArtGallery'
import ArtistPage from './components/ArtistPage'
import FavsPage from './components/FavsPage'
import LocationsContainer from './components/Locations'

//Create the route configuration
render((
  <Router history={browserHistory}>
    <Route path="/" component={Home} />
        <Route path="locations" component={LocationsContainer} />
        <Route path="artists" component={Artists} /> 
        <Route path="gallery" component={Gallery} />     
      <Route path="favorites" component={FavsPage} />
      <Route path=":artistName" component={ArtistPage} />
  </Router>
), document.getElementById('app'))

나를 extends React.Component위해 마지막 에 쓰는 것을 잊었을 때 일어났습니다 . 나는 그것이 당신이 가진 것이 아니라는 것을 알고 있지만,이 답변을 읽는 다른 사람들이 이것으로부터 이익을 얻을 수 있기를 바랍니다.


tl; dr

React Router v4를 <Route/>사용하는 경우 실제로 component소품을 사용 하여 클래스 기반 React 구성 요소를 전달 하는지 확인하십시오 !

더 일반적으로 : 클래스가 괜찮은 것처럼 보이면 클래스를 호출하는 코드가 함수로 사용하려고 시도하지 않는지 확인하십시오.

설명

나는 내가 사용했기 때문에이 오류가 발생했습니다 라우터 V4를 반응 실수로 사용 된 render소품 대신 component<Route/>수업이었다 내 구성 요소를 전달하는 구성 요소를. render함수를 기대 (호출)하고 componentReact 컴포넌트에서 작동 하는 함수 이므로 문제가되었습니다 .

따라서이 코드에서 :

<HashRouter>
    <Switch>
        <Route path="/" render={MyComponent} />
    </Switch>
</HashRouter>

<Route/>컴포넌트를 포함하는 행 은 다음과 같이 작성되어야합니다.

<Route path="/" component={MyComponent} />

그들이 그것을 확인하지 않고 그러한 실수를 쉽게 잡기 위해 사용 가능한 오류를주는 것은 부끄러운 일입니다.


나에게 그것은 new애니메이션 상태를 설정할 때 키워드 를 사용하는 것을 잊었 기 때문 입니다.

예 :

fadeAnim: Animated.Value(0),

fadeAnim: new Animated.Value(0),

그것을 고칠 것입니다.


내가 사용했기 때문에 나에게 일어난

PropTypes.arrayOf(SomeClass)

대신에

PropTypes.arrayOf(PropTypes.instanceOf(SomeClass))


ES6구성 요소 클래스가 확장되지 않아서 같은 문제가 발생했습니다 React.Component.


export default선언 이 중복되었습니다 . 첫 번째 것은 실제로 함수 인 두 번째로 재정의됩니다.


나를 위해, ComponentName.prototype대신 했습니다 ComponentName.propTypes. PhpstormIDE에서 자동으로 제안합니다 . 누군가에게 도움이되기를 바랍니다.


반응에서 컴포넌트 확장을 놓치면 대부분 이러한 문제가 발생합니다 .

import React, {Component} from 'react'

export default class TimePicker extends Component {
    render() {
        return();     
    }
}

나를 위해 propTypes 대신 프로토 타입을 사용했기 때문에

class MyComponent extends Component {

 render() {
    return <div>Test</div>;
  }
}

MyComponent.prototype = {

};

그것은되어야한다

MyComponent.propTypes = {

};

Post.proptypes = {

}

Post.propTypes = {

}

누군가는 이러한 오류를 매우 정확하게 모니터링하는 방법에 대해 언급해야합니다.


이 오류가 표시 될 때 단일 사례가없는 것 같습니다.

statefull 구성 요소에서 생성자를 선언하지 않으면 나에게 일어났습니다.

class MyComponent extends Component {

    render() {
        return <div>Test</div>;
    }
}

대신에

class MyComponent extends Component {

    constructor(props) {
        super(props);
    }

    render() {
        return <div>Test</div>;
    }
}

이것은 일반적인 문제이며 단일 사례에는 나타나지 않습니다. 그러나 모든 경우에 공통적 인 문제 import는 특정 구성 요소 를 잊어 버린다는 것입니다 (설치 한 라이브러리 또는 사용자가 만든 사용자 정의 구성 요소 중 하나인지 여부는 중요하지 않음).

import {SomeClass} from 'some-library'

나중에 가져 오지 않고 사용하면 컴파일러는 그것이 함수라고 생각합니다. 따라서 고장납니다. 이것은 일반적인 예입니다.

imports

...code...

그런 다음 코드 내부 어딘가에

<Image {..some props} />

구성 요소를 가져 오는 것을 잊어 버린 경우 <Image />컴파일러는 다른 가져 오기와 마찬가지로 불평하지 않지만 코드에 도달하면 중단됩니다.


비슷한 방법으로 render 메소드를 잘못 호출했습니다.

오류가 발생했습니다 :

render = () => {
    ...
}

대신에

correct:

render(){
    ...
}

I had it when I did so :

function foo() (...) export default foo

correctly:

export default  () =>(...);

or

const foo = ...
export default foo

For me it happened because I didn't wrap my connect function properly, and tried to export default two components


I faced this error when I imported the wrong class and referred to wrong store while using mobx in react-native.

I faced error in this snippet :

import { inject, Observer } from "mobx-react";

@inject ("counter")
@Observer

After few corrections like as below snippet. I resolved my issue like this way.

import { inject, observer } from "mobx-react";

@inject("counterStore")
@observer

What was actually wrong,I was using the wrong class instead of observer I used Observer and instead of counterStore I used counter. I solved my issue like this way.


In file MyComponent.js

export default class MyComponent extends React.Component {
...
}

I put some function related to that component:

export default class MyComponent extends React.Component {
...
}

export myFunction() {
...
}

and then in another file imported that function:

import myFunction from './MyComponent'
...
myFunction() // => bang! "Cannot call a class as a function"
...

Can you spot the problem?

I forgot the curly braces, and imported MyComponent under name myFunction!

So, the fix was:

import {myFunction} from './MyComponent'

I experienced this when writing an import statement wrong while importing a function, rather than a class. If removeMaterial is a function in another module:

Right:

import { removeMaterial } from './ClaimForm';

Wrong:

import removeMaterial from './ClaimForm';

I received this error by making small mistake. My error was exporting the class as a function instead of as a class. At the bottom of my class file I had:

export default InputField();

when it should have been:

export default InputField;

For me, it was because I'd accidentally deleted my render method !

I had a class with a componentWillReceiveProps method I didn't need anymore, immediately preceding a short render method. In my haste removing it, I accidentally removed the entire render method as well.

This was a PAIN to track down, as I was getting console errors pointing at comments in completely irrelevant files as being the "source" of the problem.


I have also run into this, it is possible you have a javascript error inside of your react component. Make sure if you are using a dependency you are using the new operator on the class to instantiate the new instance. Error will throw if

this.classInstance = Class({})

instead use

this.classInstance = new Class({})

you will see in the error chain in the browser

at ReactCompositeComponentWrapper._constructComponentWithoutOwner

that is the giveaway I believe.


Try stopping you HMR and hit npm start again to rebuild you project.
This ,made the error to disappear, don't know why.


In my case i wrote comment in place of Component by mistake

I just wrote this.

import React, { Component } from 'react';

  class Something extends Component{
      render() {
          return();
     }
  }

Instead of this.

import React, { Component } from 'react';

  class Something extends comment{
      render() {
          return();
     }
  }

it's not a big deal but for a beginner like me it's really confusing. I hope this will be helpfull.


In my case, using JSX a parent component was calling other components without the "<>"

 <ComponentA someProp={someCheck ? ComponentX : ComponentY} />

fix

<ComponentA someProp={someCheck ? <ComponentX /> : <ComponentY />} />

Another report here: It didn't work as I exported:

export default compose(
  injectIntl,
  connect(mapStateToProps)(Onboarding)
);

instead of

export default compose(
  injectIntl,
  connect(mapStateToProps)
)(Onboarding);

Note the position of the brackets. Both are correct and won't get caught by either a linter or prettier or something similar. Took me a while to track it down.


In my case, I accidentally put component name (Home) as the first argument to connect function while it was supposed to be at the end. duh.

This one -surely- gave me the error:

export default connect(Home)(mapStateToProps, mapDispatchToProps)

But this one worked -surely- fine:

export default connect(mapStateToProps, mapDispatchToProps)(Home)

This occured when I accidentally named my render function incorrectly:

import React from 'react';

export class MyComponent extends React.Component {
  noCalledRender() {
    return (
      <div>
        Hello, world!
      </div>
    );
  }
}

My instance of this error was simply caused because my class did not have a proper render method.


Actually all the problem redux connect. solutions:

Correct:

export default connect(mapStateToProps, mapDispatchToProps)(PageName)

Wrong & Bug:

export default connect(PageName)(mapStateToProps, mapDispatchToProps)

Two things you can check is,

class Slider extends React.Component {
    // Your React Code
}

Slider.prototypes = {
    // accessibility: PropTypes.bool,
}
  • Make sure that you extends React.Component
  • Use prototypes instead of prototype (as per IDE intellisense)

For me it was a wrong import of a reducer in the rootReducer.js. I imported container instead of reducer file.

Example

import settings from './pages/Settings';

But sure it should be

import settings from './pages/Settings/reducer';

Where settings directory contains following files actions.js, index.js, reducer.js.

To check it you can log reducers arg of the assertReducerShape() function from the redux/es/redux.js.

참고URL : https://stackoverflow.com/questions/38481857/getting-cannot-call-a-class-as-a-function-in-my-react-project

반응형