我想知道是否应该在 React 组件中使用属性(不是 props,不是 state)?
例如,
var myComponent = React.createClass ({
_text: '', // Something like this, a property other than props or state
});
优点和缺点是什么?用例是什么?
最佳答案
属性非常适合存储与 View 无关的数据,但对于修改行为很有用。
为什么不使用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>;
}
});
一些现实世界的例子:
- 订阅和取消订阅事件发射器
- 如果您需要生成多个 Canvas 上下文,则拥有一个 Canvas 上下文池
关于reactjs - 我应该在 React 中使用属性(除了 props 或 state)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32424360/