我'allowed'修改构造函数中的道具吗?



他们说您不应该在React组件中修改props。这是否扩展到在构造函数中修改它们?

特别是

export default class BookingForm extends React.Component {
    constructor(props) {
        // am I allowed to modify `props` here?
        super(props);
    }
}

要完全清楚,我知道JavaScript可以让我这样做,我问这是否是一种不好的设计模式,将来会使我头痛。

我想在初始化时重新格式化一些道具;之后他们不会再改变。

重新介绍Zerkms向我指出的内容,答案是 no ,您是 not not 允许修改props,甚至在构造函数中。

super()期望您获得的完全相同的道具,即使您试图通过提供不同的东西来欺骗系统,它们也会在构造函数之后立即被覆盖。ergo,您无法修改this.props

即使您尝试修改props对象以添加额外的属性,您也会看到这样的错误:

TypeError:无法添加培根,对象不可扩展

因此,即使您愿意,您也无法修改构造函数中的道具。

但是,您 can 设置了新的[JavaScript]属性,例如。

this.myReformattedProperty = format(props.oldProperty)

您无法修改props,甚至不能在构造函数中进行修改,但是您可以修改道具。示例:

constructor(props) {
  // This won't work. You will get "TypeError: Cannot add property aNewProp, object is not extensible" error.
  // props.aNewProp = 'someValue';
  // This won't work either. You will get "TypeError: Cannot assign to read only property 'anExistingProp' of object '#<Object>'" error.
  // props.anExistingProp = 'someValue';
  // However, this will work perfectly:
  props.anExistingProp.anExistingOrNewPropertyInThatProp = 'someValue';
  super(props);
}
render() {
  console.log('this.props are:');
  console.log(this.props);
  // The print-out includes the modifications that has been made to an existing prop.
}

最新更新