【问题标题】:React: this.state is undefined反应:this.state 未定义
【发布时间】:2023-03-31 22:30:01
【问题描述】:

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

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

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和范围的概念以及如何实现@987654326 @在我的情况下,如果是这种情况,请帮助我或在这里向我提出问题。

提前谢谢你。

【问题讨论】:

  • 您可能会惊喜地发现console.log(this) 的战略位置可以帮助您了解正在发生的事情。
  • @Wyck 是的,我知道至少状态正在改变,但未定义。

标签: javascript reactjs jsx


【解决方案1】:

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

//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】:
    onClick={() => {
      this.setState({modelImage: model[index]})
      ...
    }
    

    不要在onClick 方法中传递index。因为你已经在父函数中传递了index(即map方法)

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

    【讨论】:

    • 谢谢,我没有注意到与状态无关的小错误。
    【解决方案3】:
    //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>
            )
        }
    }
    
    

    【讨论】:

    • 我建议您添加一些文字来解释什么只是代码墙答案。如果答案内嵌在 cmets 中,那么它往往会在没有介绍的情况下丢失。
    • 只需阅读一点关于 js 中上下文的内容。长话短说的人。 this, bind
    • @robert 我不明白,而且更改的行也无济于事。
    • doing... 绑定方法处理单击以索引并将它们附加到 onClick 事件。您创建的 handleClick 女巫版本具有索引和上下文的分配值。我还告诉过你,你不能在更新后直接检查状态值,因为 setState 是异步的
    猜你喜欢
    • 1970-01-01
    • 2018-05-09
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    • 2018-07-06
    相关资源
    最近更新 更多