【问题标题】:Should I use properties (other than props or state) in React?我应该在 React 中使用属性(除了 props 或 state)吗?
【发布时间】:2015-09-06 14:00:31
【问题描述】:

我想知道我是否应该在 React 组件中使用属性(不是 props,不是 state)?

例如,

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

有什么优缺点,有哪些用例?

【问题讨论】:

  • 根据我的经验,你可以用属性做的几乎所有事情,你都可以用state做。
  • @SalehenRahman 但是如果我没记错的话,setState 会导致重新渲染作为副作用?
  • 我问了一个与此相关的问题:stackoverflow.com/questions/32372646/…。所以这是一个可能的用例。
  • 如果在渲染使用状态下使用了值。如果仅在方法中使用,请使用属性。
  • @YiFeng 我说的差不多了。有些情况是必要的。比如 Clarkie 提到的资源清理。

标签: reactjs react-native


【解决方案1】:

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

为什么不state 或props? state 最好在调用setState 时进行修改。但是调用setState 也会调用render,导致性能开销。虽然,我们可以通过覆盖componentShouldUpdate 来取消render 调用,但这会使事情变得过于复杂。所以,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>;
  }
});

一些现实世界的例子:

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

【讨论】:

    猜你喜欢
    • 2016-10-17
    • 2016-12-26
    • 2019-02-02
    • 1970-01-01
    • 2018-11-13
    • 2017-02-07
    • 2011-01-21
    • 2018-09-25
    • 1970-01-01
    相关资源
    最近更新 更多