首页 文章

setState更改状态但不重新呈现

提问于
浏览
2

我的第一个反应项目的第二个问题,而不是 grab 为什么我似乎无法在组件中实现渲染 .

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

下面,您将看到我正在尝试做的骨架 . 此DisplayLightbox组件从显示它的父组件中获取showLightbox = true prop(当css类lb-active添加到div时,隐藏显示) . 当我单击图像上的onClick时,我看到新的url使用console.log(this.state.activeImage)更改了displayImage函数内的状态,所以看起来不错,但渲染中没有任何变化 . 我甚至将状态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 回答

  • 3

    为了更新状态,您需要将其称为功能,而不是直接设置其属性 .

    代替:

    this.state = {
      activeImage: newImage
    }
    

    利用:

    this.setState({
      activeImage: newImage
    })
    

    请注意 this.setStateasynchronous因此 this.state.activeImage 将不会在下一行更新(如果您之后尝试 console.log

相关问题