我有一个Image类,该类允许我从containiner Component更改图像并更新图像样式。
我的课:
import React from "react";
import Radium from 'radium';
class StateImage extends React.Component {
constructor(props) {
super(props);
this.state = {
images: this.props.images.map(image => ({
...image,
loaded: false,
activeStyle: {visibility: 'hidden'}
})),
activeMode: props.activeMode
};
this.state.images.forEach((image, index) => {
const src = image.image;
const primaryImage = new Image();
primaryImage.onload = () => {
const images = [...this.state.images];
images[index].loaded = true;
if (images[index].name === this.state.activeMode) {
images[index].activeStyle = images[index].style;
// is this image the default activated one? if so, activate it now that it's loaded.
images[index].onActivate();
} else
images[index].activeStyle = {visibility: 'hidden'};
this.setState( {
...this.state,
images
});
};
primaryImage.src = src;
});
}
updateImageStyle = (name, style) => {
let images = [...this.state.images].map( (image) => {
if (image.name === name) {
return {
...image,
style: style,
activeStyle: style
}
} else return image;
});
this.setState({
...this.state,
images: images
}, () => {
console.log("updated state");
console.log(this.state);
});
};
onClick = () => {
this.state.images.map( (image) => {
if (image.clickable && image.name === this.state.activeMode)
this.props.eventHandler(this.state.activeMode);
});
};
render () {
console.log("render");
console.log(this.state.images);
let images = this.state.images.map((image, index) => {
return <img
key={ index }
onClick={ this.onClick }
style={ image.activeStyle }
src={ image.image }
alt={ image.alt}/>
});
return (
<div>
{images}
</div>
);
}
}
export default Radium(StateImage);
我的问题与updateImageStyle
有关。调用此函数时,我需要更改活动图像的style
元素并重新渲染,以便用户看到更改。
updateImageStyle
已到达,我更新了images
的{{1}}部分。 state
完成后,我console.log
进行了更改,我可以验证更改是否正确!
但是,我也从setState
进行console.log,令我惊讶的是,从render
输出的this.state.images
很旧,无法反映我的更改。
怎么可能? render
证明状态为console.log
的陈旧状态称为render
,直到我确认更改已完成。
答案 0 :(得分:1)
您很可能会看到您的状态被另一个setState调用覆盖,也许是primaryImage.onload
中的那个。由于React批次setState
一起调用,因此render()
在更新中仅被调用一次。