简体   繁体   English

使用父组件的道具设置状态

[英]Set State with Props from Parent Component

Is there a way to set the state in a Component with the Props the Component receives from a Parent Component? 有没有一种方法来设置stateComponentPropsComponent从接收Parent Component?

export default class SomeComp extends Component {
    constructor(props) {
        super(props);

        this.state = someProps; // <-- I need the props to be the state of the Component
    }


    render() {
        const { someProps } = this.props;
        ...
    }
}

Or can I write a function, something like 或者我可以写一个函数,比如

export default class SomeComp extends Component {
    constructor(props) {
        super(props);

    }

    _setProps = (someProps) => {
          this.State = someProps;
    }

    render() {
        const { someProps } = this.props;
        this._setProps(someProps);
        ...
    }
}

As Mayank Shukla mentioned, it is bad practice to store parent props in a childs state, thus managing the state within the child. 正如Mayank Shukla所提到的,将父道具存储在孩子状态是不好的做法,从而管理孩子内的状态。

The whole idea of passing down the props to the child is, that you needn't care about state within the child, because it's all trickling down from the parent. 将道具传递给孩子的整个想法是,你不必关心孩子内部的状态,因为这一切都是从父母那里流下来的。

Child components should only care about their state. 子组件应该只关心它们的状态。

What you should do instead (and what is good react practice) is to have the state in the parent component and pass event handlers down to the child which will change the state on the parent. 您应该做什么(以及什么是好的反应实践)是在父组件中具有状态并将事件处理程序传递给将改变父项状态的子项。

// in parent
class MyParentComponent extends React.Component {
  constructor() {
    super();
    this.state = {
      data: someData;
    };
  }

  handleChange(data) {
    this.setState(data);
  }

  render() {
    return (
      <MyChildComponent
        data={this.state.data}
        handleChange={this.handleChange}
      />
    );
  }
}



class MyChildComponent extends React.Component {
  // this is going to update the data in parent
  // and trickle it back down to the child
  this.props.handleChange({ foo: 'bar' });
}

The recommendation is to keep the kids states in the parent component. 建议将孩子状态保持在父组件中。 So the parent.state will eventually contain children section, where the kids states can be stored under unique ids. 所以parent.state最终会包含children节,其中孩子们的状态可以存储在唯一的id下。

this.state = {
     title: 'Some title',
     // other local stateful attributes
     children:{
        kidId1:{
          kidAttr1:' 'value'
        },
        ....
        kidId100:{
          kidAttr1:' 'value'
        }
     }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM