我应该在React中使用属性(除了props或state)吗?

时间:2015-09-06 14:00:32

标签: reactjs react-native

我想知道我是否应该在React组件中使用属性(而不是道具,而不是状态)?

例如,

var myComponent = React.createClass ({
    _text: '',   // Something like this, a property other than props or state
});

有什么优点和缺点,以及用例是什么?

1 个答案:

答案 0 :(得分:6)

属性非常适合存储与视图无关的数据,但对修改行为很有用。

为什么不stateprops?理想情况下,在调用state时应修改setState。但是调用setState也会调用render,从而导致性能开销。尽管如此,我们可以通过覆盖render取消componentShouldUpdate来电,但这会让事情变得太复杂。所以,state不是最好的地方。 props似乎是一个很好的候选人,但是,它可能会超出我们的控制范围,因此也不理想。

示例用例:您在componentDidMount中分配了一个需要清理的资源。最好的地方是componentWillUnmount。但是,您如何确定分配了哪些资源?您使用属性。

React.createClass({
  componentDidMount() {
    // `allocateResource` is entirely made up, but functions like it exist.
    this.someResourcePointer = allocateResource();
  },

  componentWillUnmount() {
    // `deallocateResource` is also entirely made up.
    deallocateResource(this.someResourcePointer);
  },

  render() {
    return <div>{/* ... */}</div>;
  }
});

一些现实世界的例子:

  • 订阅和取消订阅活动发射器
  • 拥有一个画布上下文池,如果你需要生成多个画布上下文