繁体   English   中英

React:无法添加属性“X”,对象不可扩展

[英]React : cannot add property 'X', object is not extensible

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

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

console.log(tempProps);

你不能修改this.props 这里tempProps是参考this.props所以这是行不通的。 您应该使用JSON.parse()JSON.stringify()创建props的副本

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

console.log(tempProps);

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

props 不是可变的,你不能向它们“添加”任何东西。 如果你想“复制”它们,那么你需要做

const tempProps = {...this.props};

我认为您需要添加更多道具的唯一原因是将其传递给一个孩子,但您可以在不将其添加到道具对象的情况下做到这一点。

编辑:添加带有额外道具的道具

<Component {...this.props} legendPosition="right" />

我想将更新的道具发送到子组件,如果可以不复制或克隆到新对象,请帮助我如何实现这一点。

解决方案很简单:

<ChildComponent {...this.props} legendPosition="right" />

当然, legendPosition将通过this.props.legendPositionChildComponent this.props.legendPosition

当然,更早的this.props可以包含已经legendPosition属性/值,这些属性/值将被稍后定义的顺序问题覆盖。

当然,可以有许多扩展运算符 - 对于多个属性,逻辑块......无论:

const additonalProps = {
  legendPosition: 'right',
  sthElse: true
}
return (
  <ChildComponent {...this.props} {...additonalProps} />
)

你的答案就在这一行。

var tempProps = this.props;

this.props 是不可变的,这意味着你不能改变函数中的属性值。 你可以使用 this.state 这样你就可以在你的函数中修改它

  1. props --- 你不能改变它的值。
  2. 状态 --- 您可以在代码中更改其值,但在渲染发生时它将处于活动状态。

下面在tempProps对象spread运算符中复制您的this.props对象,在spread运算符之后,我们可以添加新的对象属性,或者我们可以更新现有的对象属性。

 var tempProps = { ...this.props, tempProps.legendPosition = 'right' //property you want to add in props object };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM