3
我想知道是否应该在React组件中使用属性(不是道具,不是状态)?我应该在React中使用属性(道具或状态除外)吗?
例如,
var myComponent = React.createClass ({
_text: '', // Something like this, a property other than props or state
});
哪些利弊,和用例是什么?
我想知道是否应该在React组件中使用属性(不是道具,不是状态)?我应该在React中使用属性(道具或状态除外)吗?
例如,
var myComponent = React.createClass ({
_text: '', // Something like this, a property other than props or state
});
哪些利弊,和用例是什么?
属性非常适合存储与视图无关的数据,但对于修改行为很有用。
为什么不是state
或props
?当致电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>;
}
});
一些真实世界的例子:
要我的经验几乎可以用物业做的一切,你可以用'国家'来做。 –
@SalehenRahman但如果我没有错,setState会导致重新渲染副作用? – YiFeng
我问了一个在这里相关的问题:http://stackoverflow.com/questions/32372646/how-should-unsubscribe-be-handled-in-a-react-component-when-using-redux。所以这是一个可能的用例。 – Clarkie