简体   繁体   中英

How can i initialize state by passing props from parent component to child component in ReactJS?

I am trying to initialize state in child component (EditUser) by passing props from below parent component (App) :

class App extends React.Component{
state = { name: '', city: '', company: ''};
inApp = async (name,city,company) =>{
       await this.setState({name: name, city: city, company:company});
     }
render(){
    return(

        <div className="ui container grid">
             <div className="ui row">
                 <div className="column eight wide">
                    <UserList inApp={this.inApp}/>
                 </div>
                <div className="column eight wide">
                    <EditUser sendState={this.state}/>
                </div>
            </div>
        </div>   
       ); 
    };
};

Below is the EditUser component:

class EditUser extends React.Component{
        state = {term: this.props.sendState.name, city: this.props.sendState.city, company: this.props.sendState.company};
        change = () => {
            this.props.change(this.state.term, this.state.city, this.state.company);
        }

        render(){
           return (
                <div className="ui form">

                    <h3 className="ui dividing header">Edit User</h3>
                    <div className="field">
                        <label>Name</label>
                        <input type="text" name="name"  value = {this.state.term} onChange={e=>this.setState({term:e.target.value})} placeholder={this.props.user.name}/>
                    </div>
                   <button className="ui green button" onClick={this.change}>Submit</button>                 
              </div>  
            );
        }
};
const mapStateToProps=(state)=>{

    return {
        user: state.list.SelectUser
    };
}
export default connect(mapStateToProps, {change : change})(EditUser);

I want to initialize the state in above component.
How can i do so?

You can do it by adding a constructor to your EditUser component.

constructor(props) {
  super(props);
  this.state = {
    term: props.sendState.name, 
    city: props.sendState.city, 
    company: props.sendState.company,
  }
}

When you initialize the state within the consturctor, updated prop from the parent would not update the child's state.

You'd want to sync the state using getDerivedStateFromProps to keep the internal state up to date with the prop changes. (Do not use componentWillReceiveProps as it is now unsafe).

It's pretty tricky to get it right, so I will refer you to the official documentation, Y ou Probably Don't Need Derived State , with which you can figure out which approach to use for your use case.

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