最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Memo Feature gives :- Uncaught Error: Element type is invalid: expected a string but got: object - Stack Over

programmeradmin2浏览0评论

I have functional ponent below:-

import React from 'react'
import { Dropdown } from 'semantic-ui-react'
const DropDownMenu= (props)=> {

const options = [
    { key: 'fruits', text: 'fruits', value: 'Fruits' },
    { key: 'vegetables', text: 'vegetables', value: 'Vegetables' },
    { key: 'home-cooked', text: 'home-cooked', value: 'Home-Cooked' },
    { key: 'green-waste', text: 'green-waste', value: 'Green-Waste' },
    { key: 'other', text: 'other', value: 'other' },

];

function onChangeHandler(e) {
  console.log(e.target.innerText);
  props.getCategoryValue(e.target.innerText);
};

return (
        <Dropdown placeholder='Category' fluid selection options={options} 
 onChange={onChangeHandler} />
    );

};

export default React.memo(DropDownMenu);

Above functional ponent is being rendered in its parent ponent sellForm.js as below:-

import React,{Component} from 'react'
import { Button, Form} from 'semantic-ui-react'
import AutoCompleteInput from '../GoogleAutoplete/autoComplete';
import DropDownMenu from '../DropDown/DropDown';
import update from 'react-addons-update';
import './sellForm.css';
import PreviewImages from '../PreviewImage/previewUploadedImages';
import FileInput from '../FileInput/FileInput';

class sellForm extends Component{
constructor(props){
    super(props);
    //this.imageUpload = React.createRef();
    this.state={
        postID: '',
        title: '',
        description:'',
        category:'',
        price: '',
        amount: '',
        freshness: '',
        contact: '',
        location: '',
        timestamp: '',
        images: []
    }
}

getCategoryValue=(category)=>{
    this.setState({category: category})
};

getItemLocation=(locationObject)=>{
    this.setState({location: locationObject})
};

saveInfo=(e)=>{
    this.setState({
        [e.target.name]:e.target.value});
};

postButtonClickHandler=()=>{
    console.log(this.state)
    console.log(typeof (this.state.images[0].file))
    // send this info to firebase database
};

 handleImageUpload= (file)=>{
     console.log('handle image Upload in sell form');
     this.setState({
         images: update(this.state.images, {$push: [file]})
     })

 };

 handleImageDeletion=(indexOfImage)=>{
     console.log('handle image deletion in sell form - index to be deleted is : ' ,indexOfImage);
     this.setState((prevState)=>{
         return{
             // images: prevState.images.splice(indexOfImage,1)
             images: update(this.state.images, {$splice: [[indexOfImage,1]]})
         }
     })
 };

shouldComponentUpdate(nextProps,nextState){
    console.log('[sellform.js] shouldComponentUpdate');
    return true;
}

ponentDidMount(){
    console.log('[sellform.js] ponentDidMount');
}

static getDerivedStateFromProps(props, state){
    //when user uploads or deletes images, then props changes
    //this lifecycle executes when function gets new props before render()
    //only use when ponent's inner state depends upon props...
    console.log('[sellform.js] getDerivedStateFromProps')
    return null;
}
ponentDidUpdate(prevProps){
    console.log('[sellform.js] ponentDidUpdate')
}

ponentWillUnmount(){
    console.log('[sellform.js] ponentWillUmMount')
}

render(){
    console.log('render of sellForm');
    console.log(this.state.images);

    let previewImages = (<PreviewImages deleteUploadedImage={this.handleImageDeletion} images={this.state.images}/>)

    return(
        <Form>
            <Form.Field>
                <DropDownMenu getCategoryValue={this.getCategoryValue}/>
            </Form.Field>

            <Form.Field>
                {<AutoCompleteInput
                    onChange={()=>{}}
                    onPlaceSelected={this.getItemLocation}/>}
            </Form.Field>

            <Form.Field>
                <input
                    placeholder='What are you selling ?'
                    name="title"
                    onChange={this.saveInfo}/>
            </Form.Field>

            <Form.Field>
                <input
                    placeholder='Price'
                    name="price"
                    onChange={this.saveInfo} />
            </Form.Field>

            <Form.Field>
                    <FileInput appendImageToArray={this.handleImageUpload}/>
            </Form.Field>

            <Form.Field>
                <Button
                    type='submit'
                    onClick={this.postButtonClickHandler}>Post
                </Button>

            </Form.Field>

            <Form.Field>
                <div className='previewImageContainer'>
                    {previewImages}
                </div>
            </Form.Field>

        </Form>
    )
}
}



export default sellForm

when sellFom renders it gives following error:- Uncaught Error: Element type is invalid: expected a string (for built-in ponents) or a class/function (for posite ponents) but got: object.

Check the render method of sellForm. at invariant (react-dom.development.js:57)

Any ideas react munity ??

I have functional ponent below:-

import React from 'react'
import { Dropdown } from 'semantic-ui-react'
const DropDownMenu= (props)=> {

const options = [
    { key: 'fruits', text: 'fruits', value: 'Fruits' },
    { key: 'vegetables', text: 'vegetables', value: 'Vegetables' },
    { key: 'home-cooked', text: 'home-cooked', value: 'Home-Cooked' },
    { key: 'green-waste', text: 'green-waste', value: 'Green-Waste' },
    { key: 'other', text: 'other', value: 'other' },

];

function onChangeHandler(e) {
  console.log(e.target.innerText);
  props.getCategoryValue(e.target.innerText);
};

return (
        <Dropdown placeholder='Category' fluid selection options={options} 
 onChange={onChangeHandler} />
    );

};

export default React.memo(DropDownMenu);

Above functional ponent is being rendered in its parent ponent sellForm.js as below:-

import React,{Component} from 'react'
import { Button, Form} from 'semantic-ui-react'
import AutoCompleteInput from '../GoogleAutoplete/autoComplete';
import DropDownMenu from '../DropDown/DropDown';
import update from 'react-addons-update';
import './sellForm.css';
import PreviewImages from '../PreviewImage/previewUploadedImages';
import FileInput from '../FileInput/FileInput';

class sellForm extends Component{
constructor(props){
    super(props);
    //this.imageUpload = React.createRef();
    this.state={
        postID: '',
        title: '',
        description:'',
        category:'',
        price: '',
        amount: '',
        freshness: '',
        contact: '',
        location: '',
        timestamp: '',
        images: []
    }
}

getCategoryValue=(category)=>{
    this.setState({category: category})
};

getItemLocation=(locationObject)=>{
    this.setState({location: locationObject})
};

saveInfo=(e)=>{
    this.setState({
        [e.target.name]:e.target.value});
};

postButtonClickHandler=()=>{
    console.log(this.state)
    console.log(typeof (this.state.images[0].file))
    // send this info to firebase database
};

 handleImageUpload= (file)=>{
     console.log('handle image Upload in sell form');
     this.setState({
         images: update(this.state.images, {$push: [file]})
     })

 };

 handleImageDeletion=(indexOfImage)=>{
     console.log('handle image deletion in sell form - index to be deleted is : ' ,indexOfImage);
     this.setState((prevState)=>{
         return{
             // images: prevState.images.splice(indexOfImage,1)
             images: update(this.state.images, {$splice: [[indexOfImage,1]]})
         }
     })
 };

shouldComponentUpdate(nextProps,nextState){
    console.log('[sellform.js] shouldComponentUpdate');
    return true;
}

ponentDidMount(){
    console.log('[sellform.js] ponentDidMount');
}

static getDerivedStateFromProps(props, state){
    //when user uploads or deletes images, then props changes
    //this lifecycle executes when function gets new props before render()
    //only use when ponent's inner state depends upon props...
    console.log('[sellform.js] getDerivedStateFromProps')
    return null;
}
ponentDidUpdate(prevProps){
    console.log('[sellform.js] ponentDidUpdate')
}

ponentWillUnmount(){
    console.log('[sellform.js] ponentWillUmMount')
}

render(){
    console.log('render of sellForm');
    console.log(this.state.images);

    let previewImages = (<PreviewImages deleteUploadedImage={this.handleImageDeletion} images={this.state.images}/>)

    return(
        <Form>
            <Form.Field>
                <DropDownMenu getCategoryValue={this.getCategoryValue}/>
            </Form.Field>

            <Form.Field>
                {<AutoCompleteInput
                    onChange={()=>{}}
                    onPlaceSelected={this.getItemLocation}/>}
            </Form.Field>

            <Form.Field>
                <input
                    placeholder='What are you selling ?'
                    name="title"
                    onChange={this.saveInfo}/>
            </Form.Field>

            <Form.Field>
                <input
                    placeholder='Price'
                    name="price"
                    onChange={this.saveInfo} />
            </Form.Field>

            <Form.Field>
                    <FileInput appendImageToArray={this.handleImageUpload}/>
            </Form.Field>

            <Form.Field>
                <Button
                    type='submit'
                    onClick={this.postButtonClickHandler}>Post
                </Button>

            </Form.Field>

            <Form.Field>
                <div className='previewImageContainer'>
                    {previewImages}
                </div>
            </Form.Field>

        </Form>
    )
}
}



export default sellForm

when sellFom renders it gives following error:- Uncaught Error: Element type is invalid: expected a string (for built-in ponents) or a class/function (for posite ponents) but got: object.

Check the render method of sellForm. at invariant (react-dom.development.js:57)

Any ideas react munity ??

Share Improve this question asked Oct 30, 2018 at 3:00 Manpreet SinghManpreet Singh 1582 silver badges11 bronze badges 16
  • 1 can it be this line? {<AutoCompleteInput onChange={()=>{}} onPlaceSelected={this.getItemLocation}/>} try removing curly brackets – Said Kholov Commented Oct 30, 2018 at 3:52
  • Can you try and ment the memo ment in your SellForm and check. Commenting ponents one by one will help you in identifying the exact cause – Shubham Khatri Commented Oct 30, 2018 at 6:01
  • @SaidKholov.... onChange={()=>{}} ....here i am passing only empty function.. i checked it is not issue... – Manpreet Singh Commented Oct 30, 2018 at 6:26
  • @ShubhamKhatri... i tried menting,,,, if i ment <DropDown /> in render method of SellForm... it works ..... no issue... with <DropDown /> in render method of SellForm gives same error,,,,, – Manpreet Singh Commented Oct 30, 2018 at 6:35
  • Which version of React are you using, Can you make sure you have 16.6.0 or higher version of react and react-dom – Shubham Khatri Commented Oct 30, 2018 at 6:55
 |  Show 11 more ments

2 Answers 2

Reset to default 8

I solved this issue by updating both react and react-dom to 16.6.0.

Hey I think problem is due to naming od sellForm. Ax far as know, React accepts CamelCase Name for classes. Take this example for now:

function Example() {
  // Declare a new state variable, which we'll call "count"
  return (
    <div>
      <p>Tes</p>
    </div>
  );
}
const MemoizedExample = React.memo(Example)
function exampleParent() {
  // Declare a new state variable, which we'll call "count"
  return (
    <div>
      <p>Parent</p>
       <MemoizedExample />
    </div>
  );
}

ReactDOM.render(<exampleParent />, document.getElementById("root"))
<script src="https://unpkg./[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg./[email protected]/umd/react-dom.production.min.js"></script>

<div id="root"></div>

In above I have made name as smallcase for class, see the rendering doesn't happen. If you change the name of ponent from exampleComponent to ExampleComponent It will work. Similiarly for your problem change your class name from sellFrom to SellForm :). Here is the working one with ponent name camelcase:

function Example() {
  // Declare a new state variable, which we'll call "count"
  return (
    <div>
      <p>Tes</p>
    </div>
  );
}
const MemoizedExample = React.memo(Example)
function ExampleParent() {
  // Declare a new state variable, which we'll call "count"
  return (
    <div>
      <p>Parent</p>
       <MemoizedExample />
    </div>
  );
}

ReactDOM.render(<ExampleParent />, document.getElementById("root"))
<script src="https://unpkg./[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg./[email protected]/umd/react-dom.production.min.js"></script>

<div id="root"></div>

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论