简体   繁体   中英

React: this.state is undefined

I am making a Product Display webpage using React class component, there are two parts in the page, one is Product thumbnail area(left) and the other is Big full image of the product(right), currently it looks something like this: 在此处输入图片说明

I want it like when the user clicks on the thumbnail the main big image should change accordingly to the same thumbnail image.

JSX

//React, css and all the images import

//contains all the thumbnail variable
 var thumbs = [t1, t2, t3, t4];
//Contains the Larger image in the same index order
 var model = [b1, b2, b3, b4];

export default class Display extends Component {
 
    constructor() {
        super();        
        this.state = {
        modelImage: model[0] //initially a default 1st image is to be shown
    };
  }

    render() {
        return (
       <div>
            <Navbar />
            <div className="model">
                //Thumbnails
                <div className="model-thumb">
                    {
                        // I suspect error on this line below
                        thumbs.map((thumb, index) =>
                            <img src={thumb} 
                            key={index} 
                            alt="Product-thumb" 
                            width="75px" 
                            onClick={ (index) => {
                                // Error on this line below(maybe)
                                this.setState({modelImage: model[index]}) 

                               //logs the image first time but after then always undefined
                                console.log(this.state.modelImage) 
                            }
                             } />    
                         )
                    }
                </div>
                <div className="model-image">
                    // Big Image
                    <img src={this.state.modelImage} alt="Product-image"  />
                </div>
            </div>
     </div>
        )
    }
}



In my search through various answers I found out this has something to do with scope, and bind() should be used, but I don't know the concept of this and scopes very much and how to implement bind() in my case, if that is the case please help me or suggest me the problem here.

Thank you in advance.

onClick={() => {
  this.setState({modelImage: model[index]})
  ...
}

Don't pass index in onClick method. Because you are already passing index in parent function (ie map method)

In your case index inside onClick method will be passed as event.

The onClick function for your img tag will not be passed an index, it will be passed an event . Thus, when you try this.setState({ modelImage: model[index] }) , it's equivalent to saying this.setState({ modelImage: undefined }) . If you remove index from the parentheses where you define the onClick attribute for the img tag, you should then be referring to the correct value of index from your map function:

//React, css and all the images import

//contains all the thumbnail variable
 var thumbs = [t1, t2, t3, t4];
//Contains the Larger image in the same index order
 var model = [b1, b2, b3, b4];
 
export default class Display extends Component {

constructor() {
    super();        
    this.state = {
        modelImage: model[0] //initially a default 1st image is to be shown
    };
}

handleClick = (index) => this.setState({ modelImage: model[index] });

render() {
    return (
   <div>
        <Navbar />
        <div className="model">
            //Thumbnails
            <div className="model-thumb">
                {
                    // I suspect error on this line below
                    thumbs.map((thumb, index) =>
                        <img src={thumb} 
                        key={index} 
                        alt="Product-thumb" 
                        width="75px" 
                        onClick={ () => { // note: removed "index" variable from these parentheses, which was really an "event"
                            this.handleClick(index) // now index passed here is the current index from the map function
                        }
                         } />    
                     )
                }
            </div>
            <div className="model-image">
                // Big Image
                <img src={this.state.modelImage} alt="Product-image"  />
            </div>
        </div>
 </div>
    )
}
}
//React, css and all the images import

//contains all the thumbnail variable
 var thumbs = [t1, t2, t3, t4];
//Contains the Larger image in the same index order
 var model = [b1, b2, b3, b4];

export default class Display extends Component {
 
    constructor() {
        super();        
        this.state = {
        modelImage: model[0] //initially a default 1st image is to be shown
    };
  }
   handleClick(index){
       this.setState({modelImage: model[index]}, () =>{
              console.log(this.state.modelImage)  
       })   
    // in this place state don't have new value 
    // second parameter to function setState is a callback which will be call
    // after state update       
   }

    render() {
        return (
       <div>
            <Navbar />
            <div className="model">
                //Thumbnails
                <div className="model-thumb">
                    {
                        // I suspect error on this line below
                        thumbs.map((thumb, index) =>
                            <img src={thumb} 
                            key={index} 
                            alt="Product-thumb" 
                            width="75px" 
                            onClick={this.handleClick.bind(this, index)} />    
                         )
                    }
                </div>
                <div className="model-image">
                    // Big Image
                    <img src={this.state.modelImage} alt="Product-image"  />
                </div>
            </div>
     </div>
        )
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM