【发布时间】: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