2015-09-06 63 views
3

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

例如,

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

哪些利弊,和用例是什么?

+0

要我的经验几乎可以用物业做的一切,你可以用'国家'来做。 –

+0

@SalehenRahman但如果我没有错,setState会导致重新渲染副作用? – YiFeng

+1

我问了一个在这里相关的问题:http://stackoverflow.com/questions/32372646/how-should-unsubscribe-be-handled-in-a-react-component-when-using-redux。所以这是一个可能的用例。 – Clarkie

回答

5

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

为什么不是stateprops?当致电setState时,理想情况下应修改state。但拨打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>; 
    } 
}); 

一些真实世界的例子:

  • 订阅和事件发射
  • 退订为画布背景的游泳池,如果你需要生成多个画布上下文
相关问题