[英]Is good practice to pass state as props to children?
I find myself aggregating the state on one component. 我发现自己在一个组件上聚合状态。 Normally the node I know I will re-render so changes can propagate and state is not all over the place.
通常我知道的节点我将重新渲染,因此变化可以传播,并且状态不是全部。 Lately, I've found myself passing the state of this component as props to its first children using JSX spread attributes for the most part.
最近,我发现自己将这个组件的状态作为道具传递给第一个使用JSX传播属性的孩子。 Just to be absolutely clear, this is what I mean:
为了绝对清楚,这就是我的意思:
var Child = React.createClass({
handleClick: function(){
this.props.owner.setState({
count: this.props.count + 1,
});
},
render: function(){
return <div onClick={this.handleClick}>{this.props.count}</div>;
}
});
var Parent = React.createClass({
getInitialState: function(){
return {
count: 0,
owner: this
};
},
render: function(){
return <Child {...this.state}/>
}
});
And it works ( http://jsbin.com/xugurugebu/edit?html,js,output ), you can always go back to this component to understand whats going on and keep state as minimal as possible. 它的工作原理( http://jsbin.com/xugurugebu/edit?html,js,output ),你可以随时回到这个组件来了解最新情况并尽可能保持最小状态。
So the actual question is, if that is/isn't a good practice and why. 所以实际的问题是,如果这不是一个好的做法,为什么。
The downside I can think about at the moment is that with this approach maybe every child component would always re-render when there is a state change on the owner, if that's the case I think the above is something to use on small Component trees. 我现在可以考虑的缺点是,使用这种方法,当所有者状态发生变化时,每个子组件都可能会重新渲染,如果是这种情况,我认为上面的内容可以在小组件树上使用。
Yes! 是!
State should only be set on the top level element, this ensures that data only ever flows one way through your components. 状态应仅设置在顶级元素上,这可确保数据仅在组件中单向流动。
Bear in mind, React will only render the changes that have been made since the last render, if parts of your child elements haven't been modified they will not be re-rendered to the DOM. 请记住,React将仅渲染自上次渲染以来所做的更改,如果未修改子元素的某些部分,则不会将其重新渲染到DOM。
React has a section in their docs titled lifting up state . React在他们的文档中有一个标题为提升状态的部分 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.