我想知道我是否应该在React组件中使用属性(而不是道具,而不是状态)?
例如,
var myComponent = React.createClass ({
_text: '', // Something like this, a property other than props or state
});
有什么优点和缺点,以及用例是什么?
答案 0 :(得分:6)
属性非常适合存储与视图无关的数据,但对修改行为很有用。
为什么不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>;
}
});
一些现实世界的例子: