我想知道我是否应该在React组件中使用属性(不是props,不是state)?
例如,
var myComponent = React.createClass ({
_text: '', // Something like this, a property other than props or state
});
利弊是什么,用例是什么?
属性非常适合存储与视图无关的数据,但对于修改行为很有用。
为什么不state
和props
?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>;
}
});
一些实际示例:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句