简体   繁体   中英

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?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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