javascript 将状态作为道具传递给孩子的好习惯吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29796435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:05:06  来源:igfitidea点击:

Is good practice to pass state as props to children?

javascriptreactjs

提问by stringparser

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 attributesfor the most part. Just to be absolutely clear, this is what I mean:

我发现自己将状态聚合到一个组件上。通常,我知道的节点会重新渲染,以便更改可以传播并且状态并非无处不在。最近,我发现自己在大部分情况下使用JSX 扩展属性将这个组件的状态作为道具传递给它的第一个子组件。为了绝对清楚,这就是我的意思:

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.

我目前能想到的缺点是,使用这种方法,当所有者的状态发生变化时,每个子组件可能总是会重新渲染,如果是这种情况,我认为上述内容可用于小型组件树。

采纳答案by Kristian Roebuck

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 在他们的文档中有一个部分,名为“提升状态”