2017-09-18 39 views
1

第二个问题,从我的第一反应项目,不抓,为什么我似乎不能影响在组件渲染。我读过很多关于React在调用setState(除非使用shouldComponentUpdate)时重新呈现组件和子组件的帖子,但在我的组件中,我使用console.log看到了自己的状态更改,不过在我的组件中,实际内容不会重新呈现。的setState改变状态,但不会重新渲染

下面,你会看到什么,我试图做一个骨架。此DisplayLightbox组件接受从母体成分的showLightbox =真丙显示它(当CSS类磅活性被添加到div,隐藏显示变得)。当我点击图像上的onClick,我看到新的URL改变状态displayImage使用功能的console.log(this.state.activeImage)的内部,使得似乎不错,但没有在渲染的变化。我甚至已经添加了状态activeImage作为一个div类,只是为了看看是否显示新的URL - 不,只是显示初始/图像。

如果我通过将lightboxValue设置为false关闭Lightbox并将其重新打开,将其设置为true,它确实会尊重新状态并显示第二个图像。

我猜这可能与从父母打开有关,但我有其他组件从状态改变,因此我有点困惑,为什么这个不尊重它是新的状态。

感谢

class DisplayLightbox extends React.Component { 

    constructor(props) { 
    super(props); 
    this.state = { 
     showLightbox: false, 
     lightboxValue: null, 
     activeImage: 'path/to/initial/image' 
    }; 
    // I saw others recommend binding, not sure I'm using this right 
    this.displayImage = this.displayImage.bind(this); 
    } 

// as I understand it, this should be unnecessary, as it should be true by default 
    shouldComponentUpdate(nextProps) { 
    return true 
    } 


    displayImage(newImage){ 

    if(newImage){ 
     this.state = { 
     activeImage: newImage, 
     }; 
    } 
    console.log(this.state.activeImage) // when I click the onClick below, I see the new change in my console to the new image path, so the state is changing 

    return this.state.activeImage 
    } 


    render() { 

    var lbActive = (this.props.showLightbox === true) ? "lb-active" : "" 

    return <div className={"lightbox " + lbActive }> 
     <div className={"lightbox-content " + this.state.activeImage} > 
     <img src={this.state.activeImage} onClick={() => this.displayImage('path/to/NEW/image')} 
     /> 
     </div> 
    </div>; 
    } 
} 
+1

从来没有(!)直接改变'this.state'。总是使用'setState()'。 – Chris

回答

3

为了更新你需要调用它的功能及不直接设置其属性的状态。

相反的:

this.state = { 
    activeImage: newImage 
} 

化妆用的:

this.setState({ 
    activeImage: newImage 
}) 

注意this.setStateasynchronous,因此this.state.activeImage不会对下一行进行更新(如果你尝试console.log之后)

+0

太棒了!这样可行。我会继续我自己过了多久,有多少东西试图伸手利弊之前解决这个问题。感谢您为我澄清这一点。 – user1932694

相关问题