简体   繁体   中英

How to update modal component with new props

I have a modal component for saving recipes to a list.

 modal = <Modal saveRecipe={this.saveRecipe} closeModal={this.toggleModal}/>

Also I want to use this same modal component to edit the recipe, so i do this

if(this.state.editItem){
  modal = <Modal content={editContent} saveRecipe={this.saveRecipe} closeModal={this.toggleModal}/>
  }
else{
  modal = <Modal saveRecipe={this.saveRecipe} closeModal={this.toggleModal}/>
}

so I'm able to pass down the object to be edited to Modal Component. The modal component has a text input and a textarea element.

constructor(props) {
  super(props);
  this.state = {dish: '', ingredients:[]};      
}
componentWillReceiveProps(nextProps){ 
  console.log(nextProps) // Never fired..why??     
  let {dish, ingredients} = nextProps.content
  this.setState({
    dish:dish, ingredients:ingredients
  })
}
render(){
  let {dish, ingredients} = this.state
  console.log(this.props) // {dish:"new dish", ingredients:['ingreds']}
  return(
   <div className="modal">
    <input type="text" ref="title" value={dish} />
    <textarea ref="ingredients" value={ingredients}></textarea>
   </div>
   )

I want to prepopulate the modal form elements when edit is clicked. I am able to populate the input and textarea field if I provide

let {dish, ingredients} = this.props

instead of this.state . But then the form field become uneditable. So referring to forms , I am trying to change state of Modal Component. In my code componentWillReceiveProps is never fired? How does the componentWillRecieveProps work exactly in this situation? How to update modal component with new props?

In your case you have to use componentDidMount because when editItem state is set, then you are unmounting Model component and remounting it with content prop. So in that case componentWillRecceiveProps will not get fired but componentDidMount will get fired. So move your componentWillReceiveProps logic to componentDidMount like

componentDidMount(){ 
  console.log(this.props) // Never fired..why??     
  let {dish, ingredients} = this.props.content
  this.setState({
    dish:dish, ingredients:ingredients
  })
}

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