setState改变状态但不重新渲染。

3

这是我第一个React项目中的第二个问题,但我不明白为什么无法在组件中实现渲染。

我已经阅读了很多文章,讨论了当调用setState时React如何重新渲染组件和子组件(除非使用shouldComponentUpdate),但在我的组件中,我使用console.log看到了我的状态改变,但实际内容没有重新渲染。

下面是我尝试做的事情的框架。该DisplayLightbox组件从父组件中获取showLightbox=true属性进行显示(当添加css类lb-active到div中时,隐藏变为显示)。当我点击图像上的onClick时,我使用console.log(this.state.activeImage)在displayImage函数内部看到新的url更改状态,所以这看起来很好,但渲染没有任何变化。我甚至将状态activeImage添加为div类,只是为了看看它是否显示了新的url-它并没有显示,仍然显示初始/图像。

如果我通过将lightboxValue设置为false关闭灯箱,然后再将其设置为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
1个回答

4
为了更新状态,您需要将其作为函数调用,而不是直接设置其属性。

不要这样做:

this.state = {
  activeImage: newImage
}

利用:
this.setState({
  activeImage: newImage
})

请注意,this.setState异步的,因此下一行代码(如果您尝试在之后使用console.log)中的this.state.activeImage将不会被更新。


太棒了!这个方法可行。在向专业人士求助之前,我尝试了多长时间和尝试了多少方法来解决这个问题,但我会保持沉默。感谢您为我澄清这一点。 - user1932694

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接