Getting “Cannot call a class as a function” in my React Project

后端 未结 30 723
無奈伤痛
無奈伤痛 2020-12-07 16:34

I\'m trying to add a React map component to my project but run into an error. I\'m using Fullstack React\'s blog post as a reference. I tracked down where the error gets thr

相关标签:
30条回答
  • 2020-12-07 16:50

    For me it was because i used prototype instead of propTypes

    class MyComponent extends Component {
    
     render() {
        return <div>Test</div>;
      }
    }
    
    MyComponent.prototype = {
    
    };
    

    it ought to be

    MyComponent.propTypes = {
    
    };
    
    0 讨论(0)
  • 2020-12-07 16:51

    tl;dr

    If you use React Router v4 check your <Route/> component if you indeed use the component prop to pass your class based React component!

    More generally: If your class seems ok, check if the code that calls it doesn't try to use it as a function.

    Explanation

    I got this error because I was using React Router v4 and I accidentally used the render prop instead of the component one in the <Route/> component to pass my component that was a class. This was a problem, because render expects (calls) a function, while component is the one that will work on React components.

    So in this code:

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

    The line containing the <Route/> component, should have been written like this:

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

    It is a shame, that they don't check it and give a usable error for such and easy to catch mistake.

    0 讨论(0)
  • 2020-12-07 16:52

    I had a similar problem I was calling the render method incorrectly

    Gave an error:

    render = () => {
        ...
    }
    

    instead of

    correct:

    render(){
        ...
    }
    
    0 讨论(0)
  • 2020-12-07 16:53

    For me, it was ComponentName.prototype instead of ComponentName.propTypes. auto suggested by Phpstorm IDE. Hope it will help someone.

    0 讨论(0)
  • 2020-12-07 16:54

    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 />} />
    
    0 讨论(0)
  • 2020-12-07 16:54

    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.

    0 讨论(0)
提交回复
热议问题