反应:this.state是未定义的

时间:2020-10-22 14:14:57

标签: javascript reactjs jsx

我正在使用React类组件制作一个产品展示网页,页面有两部分,一个是产品缩略图区域(左),另一个是产品的大图(右),目前看起来像这个: enter image description here

我希望当用户单击缩略图时,主要的大图像应相应地更改为相同的缩略图。

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>
        )
    }
}



在搜索各种答案时,我发现这与范围有关,应使用bind(),但我不知道this和范围的概念以及如何在我的情况下实施bind(),在这种情况下,请帮助我或在这里向我提出问题。

谢谢。

3 个答案:

答案 0 :(得分:1)

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

请勿通过index方法传递onClick。因为您已经在父函数(即map方法)中传递了index

在您的情况下,index方法内的onClick将作为事件传递。

答案 1 :(得分:1)

您的img标签的onClick函数不会传递给索引,而是会传递给event。因此,当您尝试this.setState({ modelImage: model[index] })时,就等于说this.setState({ modelImage: undefined })。如果从定义img标签的onClick属性的括号中删除index,则应该从index函数中引用map的正确值:

//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>
    )
}
}

答案 2 :(得分:0)

//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>
        )
    }
}