Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

前端 未结 30 1083
孤城傲影
孤城傲影 2020-11-22 06:53

I am getting this error:

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/funct

30条回答
  •  孤独总比滥情好
    2020-11-22 07:34

    I was having the same issue and realized that I was providing an Undefined React component in the JSX markup. The thing is that the react component to render was dynamically calculated and it ended up being undefined!

    The error stated:

    Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of C.,

    The example producing this error:

    var componentA = require('./components/A');
    var componentB = require('./components/B');
    
    const templates = {
      a_type: componentA,
      b_type: componentB
    }
    
    class C extends React.Component {
      constructor(props) {
        super(props);
      }
      
      // ...
      
      render() {
        //Let´s say that depending on the uiType coming in a data field you end up rendering a component A or B (as part of C)
        const ComponentTemplate = templates[this.props.data.uiType];
        return 
      }
      
      // ...
    }

    The problem was that an invalid "uiType" was provided and therefore this was producing undefined as result:

    templates['InvalidString']

提交回复
热议问题