React:无法添加属性“X",对象不可扩展 [英] React : cannot add property 'X', object is not extensible

查看:166
本文介绍了React:无法添加属性“X",对象不可扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的组件中接收道具.我想在这个组件中添加一个带有道具的属性LegendPosition".我无法做到这一点.请帮我解决一下这个.我已经尝试过这段代码,但没有成功:

I am receiving props in my component. I want to add a property 'LegendPosition' with the props in this component. I am unable to do that. Please help me with this. I have tried this code yet but no success:

var tempProps     = this.props;
tempProps.legendPosition = 'right';
Object.preventExtensions(tempProps);

console.log(tempProps);

推荐答案

您不能修改 this.props.这里 tempPropsthis.props 的引用,所以它不起作用.您应该使用 JSON.parse()JSON.stringify()

You can't modify this.props. Here tempProps is reference of this.props so it does not work. You should create a copy of the props using JSON.parse() and JSON.stringify()

var tempProps = JSON.parse(JSON.stringify(this.props));
tempProps.legendPosition = 'right';
Object.preventExtensions(tempProps);

console.log(tempProps);

有关深度克隆对象的更好更有效的方法,请参阅 在 JavaScript 中深度克隆对象的最有效方法是什么?

For a better and efficient way to deep clone object see What is the most efficient way to deep clone an object in JavaScript?

这篇关于React:无法添加属性“X",对象不可扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆