【问题标题】:ReactJS - ES6 class - call super() with augmented propertiesReactJS - ES6 类 - 使用增强属性调用 super()
【发布时间】:2016-02-16 16:02:41
【问题描述】:

这是我想做的:

constructor(props, store) {
  props.store = store;
  super(props);
};

我收到以下错误:

Uncaught TypeError: Can't add property store, object is not extensible

我了解 ReactJS 中的属性是不可变的。那么如何克隆,然后扩充现有属性?

更新 1

一些背景知识:我基本上是想避免this._store“私有”变量,而宁愿将它放在props 中,因为该值在对象创建时是已知的并且不会改变。

我的类层次结构如下:

import SpeakersStore from ...;
class SpeakersViewController extends ItemsViewController {
  constructor(props) {
    super(props, SpeakersStore);
  };
  ...
};

class ItemsViewController extends React.Component {
  constructor(props, store) {
    props.store = store;
    super(props);
  };
  ...
};

【问题讨论】:

  • 这里的场景是什么?我不认为你可以在 React 中做这样的事情。但我可以想象有办法解决这个问题。
  • 为什么不将 store 作为父组件或 React.createElement 调用的另一个 prop 传递?

标签: reactjs ecmascript-6


【解决方案1】:

您应该能够做到以下几点:

constructor(props, store) {
  super({...props, store});
}

如果您处于对象扩展运算符({...props} 构造)不可用的环境中,则可以使用Object.assign

constructor(props, store) {
  super(Object.assign({}, props, {store});
}

但是,如果这是 React 组件的构造函数,请注意 React.Component 的构造函数的第二个参数是 context,您将无法获得所需的行为。

【讨论】:

  • 最好使用Object.assign,因为这个问题没有提到 ES7 或 Babel。
  • 我正在使用 Babel,所以不用担心点差...您的代码很有意义,看起来应该可以工作,但我仍然得到相同的道具,即没有额外的存储。跨度>
  • 那么需要更多信息。你的班级是如何构建的?它是一个 React 组件吗? (如果是这样,请参阅我上面的最后一段)。商店是如何建造的?
猜你喜欢
  • 2017-10-24
  • 1970-01-01
  • 2018-07-25
  • 2017-06-17
  • 1970-01-01
  • 1970-01-01
  • 2023-02-24
  • 2016-06-17
  • 2018-09-06
相关资源
最近更新 更多