【问题标题】:setState changes state but doesn't re-rendersetState 更改状态但不重新渲染
【发布时间】:2018-02-27 04:59:30
【问题描述】:

我的第一个反应项目中的第二个问题,并没有理解为什么我似乎无法在组件中进行渲染。

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

在下面,您将看到我正在尝试做的事情的骨架。此 DisplayLightbox 组件从显示它的父组件中获取 showLightbox=true 属性(当将 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>;
  }
}

【问题讨论】:

  • 永远,永远(!)直接改变this.state。始终使用setState()

标签: reactjs


【解决方案1】:

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

代替:

this.state = {
  activeImage: newImage
}

利用:

this.setState({
  activeImage: newImage
})

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

【讨论】:

  • 太棒了!这样可行。在与专业人士联系之前,我会保持自己的时间和尝试解决该问题的时间和次数。感谢您为我澄清这一点。
猜你喜欢
  • 2022-11-06
  • 1970-01-01
  • 2021-03-27
  • 2021-12-18
  • 2019-10-06
  • 1970-01-01
  • 2019-11-19
  • 2018-12-31
相关资源
最近更新 更多