[英]Why am I get this warning ' Mutating `style` is deprecated' in react component render?
I am trying to set a styleObj in react component render function like this: 我正在尝试在react组件渲染函数中设置一个styleObj,如下所示:
class ImgFigure extends React.Component {
render() {
let styleObj = {};
// props.arrange is a object like this { pos: { left: '0', top: '0'}}
if (this.props.arrange.pos) {
styleObj = this.props.arrange.pos;
}
return (
<figure className="img-figure" style={styleObj}>
<img src={this.props.data.imageURL} alt={this.props.data.title} />
<figcaption>
<h2 className="img-title">{this.props.data.title}</h2>
</figcaption>
</figure>
);
}
}
but it warn me that: 但它警告我:
warning.js?0260:44 Warning:
figure
was passed a style object that has previously been mutated.warning.js?0260:44警告:
figure
已传递一个先前已突变的样式对象。 Mutatingstyle
is deprecated.不推荐使用变异
style
。 Consider cloning it beforehand.考虑事先克隆它。 Check the
render
ofImgFigure
.检查
ImgFigure
的render
。 Previous style: {left: 0, top: 0}.上一个样式:{左:0,上:0}。 Mutated style: {left: 519, top: 272}.
变异样式:{左:519,上:272}。
I've searched relative information and in most cases the style is assigned a 'NaN' or is added additional style. 我已经搜索了相关信息,并且在大多数情况下,该样式被分配为“ NaN”或添加了其他样式。 I don't know where I am wrong, could you help me?
我不知道我哪里错了,你能帮我吗?
The error is pretty self explanatory. 该错误很容易解释。 The solution maybe not so much.
解决方案可能没有那么多。 It's telling you that you passed it a reference to an object which may have been mutated since you declared it with
let
. 这是在告诉您您已传递了对一个对象的引用,该对象自从您用
let
声明它以来就可能已经发生了变异。 The correct way would be to declare it as const
. 正确的方法是将其声明为
const
。 Of course then you can't reassign it but that's ok because you shouldn't be in the first place. 当然,您不能重新分配它,但是没关系,因为您不应该放在第一位。
Instead, consider this: 而是考虑一下:
const styleObj = this.props.arrange.pos || {};
Or even better, add a defaultProps
attribute to the component and ensure this.props.arrange.pos
is always at least an empty object. 甚至更好的是,向组件添加
defaultProps
属性,并确保this.props.arrange.pos
始终至少是一个空对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.