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

YiF*_*eng 5 reactjs react-native

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

例如,

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

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

Sal*_*Sal 6

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

为什么不statepropsstate理想情况下,在调用时应该修改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>;
  }
});
Run Code Online (Sandbox Code Playgroud)

一些现实世界的例子:

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